是否可以在 Linux 中设置本地时间的计时器?

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

我正在与 raspberry pi、

进行物联网项目

我想在特定时间引发事件,例如 06:00:00 和 12:00:00

但是我不能用 jiffies 做这个,因为 jiffies 只计算自 os 开始以来的时间。

我有一个想法:

我可能会每秒引发一次中断并检查本地时间,将其与特定时间进行比较。

但我认为这是非常糟糕的方式

你对这个问题有什么好的想法吗?

提前致谢。

运行 06:00:00 和 12:00:00 的 cron。通过 cron 触发您的事件。How to create a cronjob

Crontab and cron 是 ninja 已经回答的计时方法。

如果您需要非常轻量级的解决方案,并且想使用 RTC。然后有替代解决方案:

RTC 芯片通常包含报警功能。如果中断信号从 RTC 连接到 CPU,那么您可以通过 linux 的 rtc API 使用它。

要设置和等待计时器,您需要这样的东西(不是完整的示例):

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

完整示例here

除了使用 cron,您还可以自己做 cron 做的事情。像这样:

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

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

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

需要循环来处理可能的中断;检查 clock_nanosleep(2).