Randomly Scheduled Task Execution

  • Share this:

Code introduction


This code defines a function named random_task that randomly executes one of five tasks. The code uses the Schedule library to schedule this function to run every 10 seconds.


Technology Stack : Python, Schedule

Code Type : Timed task

Code Difficulty : Intermediate


                
                    
import schedule
import time
import random

def random_task():
    tasks = ['task1', 'task2', 'task3', 'task4', 'task5']
    selected_task = random.choice(tasks)
    
    if selected_task == 'task1':
        print("Running task1")
        time.sleep(2)
    elif selected_task == 'task2':
        print("Running task2")
        time.sleep(3)
    elif selected_task == 'task3':
        print("Running task3")
        time.sleep(4)
    elif selected_task == 'task4':
        print("Running task4")
        time.sleep(5)
    elif selected_task == 'task5':
        print("Running task5")
        time.sleep(6)

# Schedule the function to run every 10 seconds
schedule.every(10).seconds.do(random_task)

# Keep the script running
while True:
    schedule.run_pending()
    time.sleep(1)