How to run Cron jobs in Python?

Better Stack Team
Updated on October 5, 2023

To run Cron jobs in Python, you can create a Python script with the code you want to run and schedule it to run using Cron. Here are the steps to create and schedule a Python script:

🔭 Want to get alerted when your Cron doesn’t run correctly?

Go to Better Stack and start monitoring in 5 minutes.

Create a Python script:

Create a Python script with the code you want to run as a Cron job. For example, let's say you want to delete all temporary files from a directory every day at midnight. You can create a Python script called cleanup.py with the following code:

 
import os
import glob

# Set the directory to clean up
dir_path = '/path/to/temp/files/'

# Get a list of all files in the directory
files = glob.glob(os.path.join(dir_path, '*'))

# Delete all files in the directory
for file in files:
    os.remove(file)

Set the correct file permissions:

Make sure that the file permissions of your Python script allow the user running the Cron job to execute it. You can set the permissions using the chmod command:

 
chmod +x cleanup.py

Schedule the Cron job:

Open the crontab file using the command crontab -e and add the following line to schedule the Cron job:

 
0 0 * * * /usr/bin/python3 /path/to/cleanup.py

This Cron job will run every day at midnight and execute the cleanup.py script using the Python 3 interpreter located at /usr/bin/python3.

Note: If you are using a Python virtual environment for your project, make sure to activate it before running the script. For example, if your virtual environment is located at /path/to/venv, you can modify the Cron job as follows:

 
0 0 * * * /path/to/venv/bin/python /path/to/cleanup.py

Verify the Cron job:

You can verify that the Cron job has been added to the crontab file by running the command crontab -l.

By following these steps, you can create and schedule a Python script to run as a Cron job.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github