Random Scheduled Task Execution in Python

  • Share this:

Code introduction


代码含义解释[英文]


Technology Stack : 代码所使用到的包和技术栈[英文]

Code Type : The type of code

Code Difficulty :


                
                    
import random
from schedule import every, run_pending

def random_task():
    # This function creates a random scheduled task using the Schedule library.

    # Define a list of possible tasks
    tasks = [
        every(1).minutes.do(lambda: print("Task 1: Every minute")),
        every(2).hours.do(lambda: print("Task 2: Every two hours")),
        every(3).days.do(lambda: print("Task 3: Every three days")),
        every(4).weeks.do(lambda: print("Task 4: Every four weeks")),
        every(5).seconds.do(lambda: print("Task 5: Every five seconds"))
    ]

    # Select a random task from the list
    selected_task = random.choice(tasks)

    # Run the selected task immediately
    selected_task()

# Code Explanation
# The function 'random_task' selects a random scheduled task from a list of predefined tasks. Each task is defined using the Schedule library's 'every' function and 'do' method. The selected task is then executed immediately using the 'run_pending' method.

# Technical Stack
# - Schedule: A Python library to schedule events and tasks.

# Explanation in English
# The function 'random_task' creates a scheduled task randomly from a predefined list using the Schedule library. Each task is set to run at a specific interval, such as every minute, hour, day, week, or second. The selected task is executed immediately after selection.

# Technical Stack in English
# - Schedule: A Python library for scheduling events and tasks.