
//一个示例程序。
#include<stdlibh>
#include<unistdh>
#include<signalh>
#include<timeh>
#include<sys/timeh>
#define N 100 //设置最大的定时器个数
int i=0,t=1; //i代表定时器的个数;t表示时间,逐秒递增
struct Timer //Timer结构体,用来保存一个定时器的信息
{
int total_time; //每隔total_time秒
int left_time; //还剩left_time秒
int func; //该定时器超时,要执行的代码的标志
}myTimer[N]; //定义Timer类型的数组,用来保存所有的定时器
void setTimer(int t,int f) //新建一个计时器
{
struct Timer a;
atotal_time=t;
aleft_time=t;
afunc=f;
myTimer[i++]=a;
}
void timeout() //判断定时器是否超时,以及超时时所要执行的动作
{
printf("Time: %d\n",t++);
int j;
for(j=0;j<i;j++)
{
if(myTimer[j]left_time!=0)
myTimer[j]left_time--;
else
{
switch(myTimer[j]func)
{ //通过匹配myTimer[j]func,判断下一步选择哪种 *** 作
case 1:
printf("------Timer 1: --Hello Aillo!\n");break;
case 2:
printf("------Timer 2: --Hello Jackie!\n");break;
case 3:
printf("------Timer 3: --Hello PiPi!\n");break;
}
myTimer[j]left_time=myTimer[j]total_time; //循环计时
}
}
}
int main() //测试函数,定义三个定时器
{
setTimer(3,1);
setTimer(4,2);
setTimer(5,3);
signal(SIGALRM,timeout); //接到SIGALRM信号,则执行timeout函数
while(1)
{
sleep(1); //每隔一秒发送一个SIGALRM
kill(getpid(),SIGALRM);
}
exit(0);
}
crontab
-e
,然后,输入
/1
这个是每隔一个小时,执行一次。。。
楼主需要的情况,at,crontab
都是无法完全满足的,因为,crontab
每次执行,只能是每隔一段时间(但是间隔时间都是相同的),或者在某个时刻,楼主这种,情况很特殊,估计,需要,编写c
程序,才可以搞定的。。。
以上就是关于求linux下用c语言编写的定时器程序全部的内容,包括:求linux下用c语言编写的定时器程序、我想在linux用c搞个 定时程序然后可以指定时间运行程序。时间是小时和分钟的。主要是分钟要可以累加。比如、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)