How to run a python script at specific times

Systemd offers multiple ways to run a script at a specific time. The first of which is the monotonic timer. This is used to run a task after another task that has no exact time, for example 10 mins after boot. I will be covering the realtime timers. These function as you would expect, much like crontab (ie on specific days and times).

A timer in systemd requires two files, the .service file and then the .timer file. I will outline below a file service file to run a python program. More detail on this can be found in my other post.

[Unit]
Description=Service description

[Service]
WorkingDirectory=/home/ryan/discord_bot/ # Directory to start in
ExecStart=/usr/bin/python3 /home/ryan/discord_bot/bot.py
User=ryan # User to run as
Restart=always # Restart if it closes

[Install]
WantedBy=multi-user.target
.service file

Below outlines a basic .timer file. The OnCalender= takes multiple parameters, one (the most granular) is shown below. Another option is something such as weekly which does what you'd expect. The commented out line, sets the program to run if the previous timer was missed, due to being shutdown for example.

[Unit]
Description=Run foo weekly

[Timer]
OnCalendar=DayOfWeek Year-Month-Day Hour:Minute:Second
#Persistent=true

[Install]
WantedBy=timers.target
.timer file

Mastodon