Explain Codes LogoExplain Codes Logo

How do I get a Cron like scheduler in Python?

python
cron
scheduling
python-library
Nikita BarsukovbyNikita Barsukov·Sep 7, 2024
TLDR

Working with Cron in Python? No sweat, use the schedule library:

import schedule # Declaring the function task def task(): print("I finished my task!") # Setting up the task to run every hour schedule.every().hour.do(task) # How to never miss your favorite TV show again! while True: schedule.run_pending()

Get it up by running pip install schedule, call your task function (named task()) with schedule.every().hour.do(task) for an hourly schedule. Give life to the scheduler using while True: schedule.run_pending().

Python in a Cron world

Python loves traditional cron expressions

Get your hands on Crontab, a wizard for Cron expressions in Python. It even manages daylight savings time!

from crontab import CronTab # Make your Python feel at home on a crontab! my_cron = CronTab(user='username') job = my_cron.new(command='python3 /path/to/script.py') job.minute.every(1) for result in my_cron.run_scheduler(): print("Ssssh! The cron is busy", result)

Concurrent jobs, in-thread execution: Python's got it all!

Need concurrency? Think no further than a Gevent-based crontab. Or for tasks cooked right within the thread, pycron has got your back.

from pycron import is_now def job(): # Time for some digital breakfast at 04:05 every day! if is_now('5 4 * * *'): print("Job served!") while True: job() time.sleep(60) # Beauty sleep for the CPU. Don't want it to burn out, do we?

No stepping on toes: Scheduling tasks without overlaps

To prevent your tasks from wearing the same tie to the party, you have to handle overlapping tasks. If you're a fan of pycron, introduce it to time.sleep(). They'll make a cute time-keeping couple, trust me!

Picking the right cron-scheduler in Python

Flexibility over complexity

When it comes to simplicity and reliability, the schedule library is your best companion. Write your tasks, not your worries!

A Cron tool for every need

Timezones giving you a nightmare? Involve Crontab for solving timezone mysteries. Got multiple tasks? Say hello to Gevent or the super cool Celery, the distributed task handler.

The crowd speaks

Votes and acceptance of a library speak a lot about its reliability. So, do your homework before choosing. However, the community's darling, schedule, is quite a star!