Random Task Scheduler with Three Different Actions

  • Share this:

Code introduction


The code defines a randomly selected task to be executed, which can be executed every 10 seconds, repeated three times, or execute all pending tasks.


Technology Stack : Schedule, random, time

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from schedule import every, repeat, run_pending
import random
import time

def random_task():
    tasks = {
        "task1": every(10).seconds,
        "task2": repeat(3),
        "task3": run_pending
    }
    
    selected_task = random.choice(list(tasks.keys()))
    selected_action = tasks[selected_task]

    if selected_task == "task1":
        # This task runs every 10 seconds
        print("Running task1 every 10 seconds.")
        while True:
            time.sleep(10)
    elif selected_task == "task2":
        # This task repeats 3 times
        for _ in range(3):
            print("Running task2, repetition #{}".format(_ + 1))
            time.sleep(5)  # Wait for 5 seconds before next repetition
    elif selected_task == "task3":
        # This task runs all pending jobs
        print("Running task3, executing all pending jobs.")
        run_pending()