0

I am trying to create a stand alone program on the raspberry pi that will run functions at specific times. I have done some research and everything seems to point to using crontab. I would ideally not like to use crontab because I want to be able to share the program later on and asking users to edit their crontab seems a bit invasive.

The program would consist of running scheduled tasks (run at a specific time each day), constant tasks (loops collecting data and displaying on an LCD every 3 seconds), and also tasks at intervals (running certain functions every 15 minutes).

My question is, what would be the most effective way of achieving this? My initial thought is to create a function that looks at the theTime tuples and if statements to determine what to run, but even as a novice, that sounds very clunky. The 'schedule' package seems promising, but I'm unsure of how to integrate scheduled tasks in the background of constantly running loops. Has anyone had any experience with making a program like this and maybe have some examples of code that has worked for them?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

2 Answers2

0

The magic word you are looking for is 'service'. These are long-running processes that the operating system launches at (for example) boot, and ideally checks periodically and restarts if necessary.

I haven't done if for the raspberry pi, but I found this which looks promising. This assumes your python script is in /root/mouse.py.

First, create a service definition in, for example, /lib/systemd/system/mouselogger.service:

[Unit]
Description=Mouse Logging Service

[Service]
ExecStart=/root/mouse.py
StandardOutput=null

[Install]
WantedBy=multi-user.target
Alias=mouselogger.service

Then, enable on the console with:

sudo systemctl enable mouselogger.service
sudo systemctl start mouselogger.service

Your script should then manage it's own sleep, for example:

from time import sleep
while True:
   sleep(2)
   print("hello!")

Another, possibly simpler option is to use crontab after all: simply run your script every minute, or every ten if that's granular enough, and just exit without doing anything if there's nothing to be done at the time.

Matthias Winkelmann
  • 15,870
  • 7
  • 64
  • 76
0

Check recent discussion

How do I get a Cron like scheduler in Python?

for few other examples, notable https://apscheduler.readthedocs.io , which has nice web page. In my own experience home grown libs or extensions suffer from summer time issues. I guess performance can be issue, new scheduling tools often have performance and other limitations, while cron is venerable, battle tested (even though early implementations were rather naive). An interesting article http://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time

Community
  • 1
  • 1
Serge
  • 3,387
  • 3
  • 16
  • 34