Python cron jobs: run a script on a schedule

On this page

To run a Python cron job, add a crontab line that names the interpreter and the script by absolute path. Cron starts with a bare environment, so a script that works in your terminal can fail there until the paths, the virtualenv and the log file are spelled out.

How do you schedule a Python script with cron?

Open the crontab with crontab -e and add one line: five schedule fields, the interpreter, the script, and a redirect for the output.

crontab -e
15 3 * * * /srv/app/.venv/bin/python /srv/app/jobs/nightly.py >> /var/log/nightly.log 2>&1

That runs nightly.py at 03:15 every day with the interpreter of the virtualenv in /srv/app/.venv. Naming the virtualenv's interpreter is enough to use its packages: there is nothing to activate. If the schedule needs a second look, paste it into the cron expression translator, or read the cron syntax cheat sheet.

Why does a Python script work in the terminal but not in cron?

  • A different PATH. Cron sets a short PATH, so python may be missing or point to another version. Use the full path from which python3.
  • No login environment. Variables from your shell profile, such as API keys, are not set. Put them in the crontab above the line, or load them from a file in the script.
  • A different working directory. Cron starts in the home directory of the user. Open files by absolute path, or cd first: cd /srv/app && .venv/bin/python jobs/nightly.py.
  • Percent signs. In a crontab line, % starts standard input unless it is escaped as \%. A date +%F in the command breaks the line.

Cron environment and PATH goes through the rest, and cron job not running is the full checklist.

How do you keep the output of a Python cron job?

Cron mails any output to the owner of the crontab, and the mail is lost on a machine with no mail system. Redirect standard output and standard error to a file, as in the line above, and let the script write its own log records with the logging module. Cron logs explains where cron itself records each start.

When should you use APScheduler or Celery beat instead?

Cron starts a new process for every run, which suits a script that does one job and exits. When the work needs a long-running process, such as an application that holds a database pool or an in-memory cache, the schedule belongs inside it. APScheduler runs jobs inside your own process, and Celery beat hands scheduled tasks to a pool of workers. Both read cron-style schedules, so the expressions on this page carry over.

How do you know the script ran?

Have the script report to a check when the work is done. The request below has a timeout and swallows its own errors, so a problem on the monitoring side can never fail the job:

nightly.py
import urllib.request

def report(suffix=""):
    try:
        urllib.request.urlopen("https://ping.cronmissed.com/5f0c1b2e-7a3d-4c8e-9b61-2d4f8a7e3c10" + suffix, timeout=10).read()
    except OSError:
        pass

def main():
    ...  # the nightly work
    report()

if __name__ == "__main__":
    try:
        main()
    except Exception:
        report("/fail")
        raise

Or leave the script alone and ping from the crontab line, which works for a script in any language:

crontab with a ping
15 3 * * * /srv/app/.venv/bin/python /srv/app/jobs/nightly.py && curl -fsS --max-time 10 --retry 5 -o /dev/null https://ping.cronmissed.com/5f0c1b2e-7a3d-4c8e-9b61-2d4f8a7e3c10

Create a check with the same schedule and CronMissed alerts you when the ping is late or the job reports a failure. The crontab guide walks through the setup.

Sources

Questions and answers

How do I run a Python cron job every 5 minutes?
Use */5 * * * * as the schedule, followed by the interpreter and script. Make sure a run can finish within 5 minutes, or two runs will overlap; see overlapping cron runs.
Do I need to activate the virtualenv in the crontab?
No. Running the interpreter inside the virtualenv, such as /srv/app/.venv/bin/python, uses that environment's packages without an activate step.
Is there a cron job library for Python?
Cron itself is a system service, not a library. To read or edit crontab files from Python there are third-party packages, and to run schedules inside Python use APScheduler or Celery beat.
Know the moment a job goes quiet

Create a check, add one curl to the job, and CronMissed alerts you when a ping is late or reports a failure.

Start monitoring