How to run Cron jobs in Python?

Better Stack Team
Updated on May 26, 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:

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.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack