# How to run Cron jobs in Python?

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:

[info]
## 🔭 Want to get alerted when your Cron doesn’t run correctly?
Go to [Better Stack](https://betterstack.com/uptime/) and start monitoring in 5 minutes.
[/info]

## 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:

```python
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:

```bash
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:

```bash
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:

```bash
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.

[ad-uptime]