简体   繁体   中英

Is it possible to set timer with local time in Linux?

I'm on my IOT project with raspberry pi,

And I want to raise event in certain time like 06:00:00 and 12:00:00

But I can't do this with jiffies because jiffies only counts the time since the os started.

I have an Idea :

I may raise interrupt every second and check local time, compare it with certain time.

But I think it is very bad way

Do you have any good idea for this problem?

Thanks in advance.

Run a cron at 06:00:00 and 12:00:00. Trigger your event through cron. How to create a cronjob

Crontab and cron is the way to do such timing as ninja already answered.

If you need very light weight solution, and want to play with RTC. Then there is alternative solution:

RTC chips usually contain an alarm functionality. If interrupt signal is wired from RTC to CPU, then you may use it via rtc API of linux.

For setting and waiting a timer you need something like this (not a complete example):

struct rtc_time rtc_tm = {....};

fd = open("/dev/rtc0", O_RDONLY, 0);  // Open the RTC device
ioctl(fd, RTC_AIE_ON, 0);             // Enable alarm interrupt
ioctl(fd, RTC_ALM_SET, &rtc_tm);      // Set the alarm time
read(fd, &x, sizeof(x));              // Wait the alarm

Complete example here .

Instead of using cron, you can do what cron does yourself. Something like this:

struct timespec target = { ... };
int ret;

while((ret = clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &target, NULL)) == EINTR)
    ;

/* if !ret, current time is $target here */

The loop is needed to handle possible interruption; check clock_nanosleep(2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM