Scheduled Random Task Execution Every Minute

  • Share this:

Code introduction


The code defines a function `scheduled_task` that uses the Schedule library's `every` and `do` methods to execute the `random_task` function every minute. The `random_task` function randomly chooses to perform an email send, database update, or file processing operation.


Technology Stack : The code defines a function `scheduled_task` that uses the Schedule library's `every` and `do` methods to execute the `random_task` function every minute. The `random_task` function randomly chooses to perform an email send, database update, or file processing operation.

Code Type : Timed task

Code Difficulty : Intermediate


                
                    
import random
from schedule import every, run_pending
from datetime import datetime

def random_task():
    # This function generates a random task that is scheduled to run every minute
    task_type = random.choice(["email", "database", "file"])
    if task_type == "email":
        # Simulate sending an email
        print(f"Sending an email at {datetime.now()}")
    elif task_type == "database":
        # Simulate a database operation
        print(f"Updating the database at {datetime.now()}")
    elif task_type == "file":
        # Simulate processing a file
        print(f"Processing file at {datetime.now()}")

def scheduled_task():
    # Schedule the random_task to run every minute
    every(1).minutes.do(random_task)
    run_pending()