Cron-Like Scheduling with Python
The need for scheduling tasks based on flexible expressions arises in various contexts. While cron serves this purpose in many environments, it may not be universally available or feasible. In such cases, Python provides several options for creating your own cron-like schedulers.
Lightweight Approach with the Schedule Library
If lightweight and pure Python-based solutions are desired, the schedule library offers a simple and expressive interface. It enables scheduling tasks using cron-like expressions:
import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) while 1: schedule.run_pending() time.sleep(1)
In this example, the job() function will execute at regular intervals. You can modify the expression to define complex schedules, such as every 2 hours between 9 am and 5 pm on weekdays.
Alternative Approaches
If the schedule library does not meet your specific requirements, consider these alternative approaches:
Remember, when defining your own scheduler, you will need to handle launching Python functions in a separate thread to avoid blocking the main process.
The above is the detailed content of How Can I Create Cron-Like Scheduling in Python?. For more information, please follow other related articles on the PHP Chinese website!