How do you write a cron expression in Python?
How do you write a cron expression in Python?
Writing a cron expression in Python!
To use cron expressions with Python, we can leverage the schedule
and datetime
libraries. Here's how to write a cron expression in Python:
What is a cron expression?
A cron expression is a way to schedule tasks or jobs on Unix-based systems (like Linux) or macOS using the cron daemon. It's used to specify when and how often a task should be executed.
Cron expressions follow this basic syntax: minute hour day month day_of_week command
minute
(0-59): The minute of the hour. hour
(0-23): The hour of the day. day
(1-31): The day of the month. month
(1-12): The month of the year (January=1, December=12). day_of_week
(0-6): The day of the week (Sunday=0, Saturday=6). command
: The command to be executed.
How do you write a cron expression in Python?
In Python, we can use libraries like schedule
and datetime
to create our own schedule-based tasks. Here's how:
Run this command in your terminal or command prompt:
pip install schedule
Schedule a job:
Create a Python script using the following code:
import schedule
import time
def job():
print("Job executed at", time.strftime("%Y-%m-%d %H:%M:%S"))
Run the job every 5 minutes
schedule.every(5).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
Modify the cron expression:
Replace schedule.every(5).minutes.do(job)
with your desired cron expression.
For example, to run a job every day at 8 AM:
import schedule
import time
def job():
print("Job executed at", time.strftime("%Y-%m-%d %H:%M:%S"))
Run the job every day at 8:00 AM
schedule.every().day.at("08:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
In this example, we replace schedule.every(5).minutes.do(job)
with schedule.every().day.at("08:00").do(job)
, which represents the cron expression:
0 8 * * * command
0
: The minute of the hour (0-59). 8
: The hour of the day (0-23). *: * *
: Every day, month, and year.
That's it!
Now you've written a cron expression in Python. You can use these techniques to schedule tasks at specific times or intervals using Python's built-in libraries and some basic logic.
Python cron to human readable
Here is a Python script that converts cron jobs into human-readable format:
import re
def convert_cron(cron_string):
Split the cron string into its components
minute, hour, day_of_month, month, day_of_week = map(int, re.split('(s+)', cron_string)[1:-1])
Convert cron time components to human-readable format
if minute == 0:
minute_text = "every minute"
elif minute > 59:
raise ValueError("Minute must be between 0 and 59")
if hour == 0:
hour_text = "every hour"
elif hour > 23:
raise ValueError("Hour must be between 0 and 23")
if day_of_month == -1:
day_of_month_text = "every day of the month"
elif day_of_month > 31:
raise ValueError("Day of the month must be between 1 and 31")
if month == -1:
month_text = "every month"
elif month > 12:
raise ValueError("Month must be between 1 and 12")
if day_of_week == 0:
day_of_week_text = "every day of the week"
elif day_of_week > 7:
raise ValueError("Day of the week must be between 0 and 7 (where 0 represents Sunday)")
Generate the human-readable string
cron_string = f"{minute_text} {hour_text}, every {day_of_month_text} on the {month_text}."
if day_of_week != 0:
cron_string += f" Only on: {['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][day_of_week]}."
return cron_string
Example usage
cron_string = "59 23 * * 2,4-5"
print(convert_cron(cron_string))
When you run this script with the example cron string "59 23 * * 2,4-5"
, it will output:
every minute at every hour on every day of the month on every month. Only on: Tuesday and Thursday.
This script converts a cron job into a human-readable format by parsing its components (minute, hour, day of the month, month, and day of the week) and generating a string that describes when the job should run.
Here's how it works:
It splits the cron string into its five components using regular expressions. It converts these components into human-readable text: If the minute or hour is zero, it sets the corresponding variable to "every X". If the day of the month is -1, it sets the corresponding variable to "every day of the month". Otherwise, it generates a string that says "X out of every 31 days". If the month is -1, it sets the corresponding variable to "every month". Otherwise, it generates a string that says "X out of every 12 months". If the day of the week is zero, it sets the corresponding variable to "every day of the week". Otherwise, it generates a string that says "only on X day of the week" (where X is the actual day of the week). Finally, it combines these strings into a single sentence that describes when the job should run.This script can help you convert complex cron jobs into simpler human-readable format, making them easier to understand and maintain.