ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

C语言实现定时任务

2022-02-25 10:31:00  阅读:272  来源: 互联网

标签:hour AutoRebootMsg reboot timer C语言 任务 tm time 定时


例:设置定时任务,每周周X的X时X分自动重启系统
思路:将设置好的重启时间保存到本地配置文件中,设置定时器定时一分钟,每一分钟信号触发一次事件,事件函数中获取配置文件信息与当前系统时间信息,将两个时间进行时间差计算,符合条件的自动重启系统.

//创建定时器函数(通过信号触发事件timer_task函数启动)

int create_timer()
{
    struct sigevent evp;  
    int ret = 0;

    memset(&evp, 0, sizeof(struct sigevent));

    evp.sigev_value.sival_ptr = &s_time_id;
    evp.sigev_notify = SIGEV_SIGNAL;
    evp.sigev_signo = SIGUSR1;
    signal(SIGUSR1, timer_task);
  
    ret = timer_create(CLOCK_REALTIME, &evp, &s_time_id);
    if (ret != 0) {
        printf("timer_create failed\n");  
        return -1;
	}
    return 0;
} 

//初始化定时器(设置定时时间)

int init_timer()
{
    int ret = 0;
    struct itimerspec ts;   
    ts.it_value.tv_sec = 60;
    ts.it_value.tv_nsec = 0;  
  
    ret = timer_settime(s_time_id, 0, &ts, NULL);
    if (ret != 0) {
		printf("timer_settime failed\n"); 
        return -1;
	}  
    return 0;
}

//事件函数(例如 : 固定每周X的X时X分重启)

void timer_task()  
{  
    time_t timep;
    struct tm *p;
    time(&timep);
    p = gmtime(&timep);

    AutoRebootConfig AutoRebootMsg = {0};
    config_get_auto_reboot_time(&AutoRebootMsg);	//获取配置文件中设定好的重启时间
   
    if (AutoRebootMsg.auto_reboot_enable == 1) {
        int tm_hour = p->tm_hour+8;
        if (tm_hour >= 24) {
            tm_hour -= 24;
        }
        
        //The current time is Sunday, and the automatic restart time is not Sunday
        if (p->tm_wday == 0 && AutoRebootMsg.auto_reboot_weekday != 0) {
            p->tm_wday = 7;
        }

        int weekday_sub = p->tm_wday - AutoRebootMsg.auto_reboot_weekday;
        if (p->tm_wday == AutoRebootMsg.auto_reboot_weekday || (weekday_sub == 1 && tm_hour == 0)) {
            if (tm_hour == 0 && AutoRebootMsg.auto_reboot_hour != 0) {
                tm_hour = 24;
            }    

            int time_sub = (tm_hour - AutoRebootMsg.auto_reboot_hour)*60 + p->tm_min - AutoRebootMsg.auto_reboot_minute;
            if (time_sub >= 0 && time_sub < 1) {
                system("reboot");
            }
        }
        create_timer();
        init_timer();
    }
} 

标签:hour,AutoRebootMsg,reboot,timer,C语言,任务,tm,time,定时
来源: https://blog.csdn.net/weixin_43793181/article/details/123127024

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有