Reputation: 17
Context:
I am working on an embedded openwrt on a retry system for http request and certificate peremption checking.
We don't trust our web server and want to make retry GET HTTP on file every days until it's downloaded.
We also want to download files at precise hours.
During regular times, the program is:
Problematic:
I want to program in C a signal every day to get asynchronous events. So i basically want crontab without crontabs.
The signal I want to use is the ones used in IPC (I don't know other way to create asynchronous behaviours on linux) : https://www.man7.org/linux/man-pages/man7/signal.7.html
I know how to use crontab but i would prefer to do everything in C as it would make my architecture simpler for my coworkers who don't use linux.
As far as i know crontab don't have a C api.
I used timers in my code but they don't seem to fit this usage: https://man7.org/linux/man-pages/man2/timer_create.2.html It should be doable to request the date and time from the system and create a timer to fire at the desired hour everyday but I thought there might be an already made solutions on Linux. Something like eventHour(hour, signal, handler).
I don't have systemd https://linuxconfig.org/how-to-schedule-tasks-with-systemd-timers-in-linux
Question: What is the proper way in C on Linux to get dayly/periodic signal ?
Many thanks,
Upvotes: 0
Views: 226
Reputation: 18503
I don't know other way to create asynchronous behaviors on Linux
Linux itself seems not to support anything that is similar to what you want.
To perform certain actions at a certain time, some program must be started and run in the background until the action shall be performed. If the action shall be performed cyclically, the program must be running permanently.
Using a crontab
has the advantage that only one program (cron
) is running in the background even if you have hundreds of different actions in your crontab
. However, one program (cron
) is running in the background permanently.
The same is true for systemd
.
If you don't want to use such a tool, your program must run in the background permanently.
timer_create
This can be used if you require a quite high precision (for example less than one second).
If you don't need a high precision and you don't want cron
or similar, I would do something like this:
seconds_per_day = 60*60*24;
next_time = time(NULL) + seconds_per_day;
while(1)
{
usleep(5000000);
if(time(NULL) >= next_time)
{
perform_action();
next_time += seconds_per_day;
}
}
In the example I use usleep()
to wait for 5 seconds. Using a longer time (e.g. 10 seconds) will reduce the CPU power consumed by your program running in the background - and make the exact point in time when you trigger your action more imprecise.
The example simply triggers one action every 24h.
However, you can use the same principle to trigger some action at a certain time (e.g. 11:30pm) or multiple actions at different times...
Upvotes: 1