日期:2014-05-16  浏览次数:20634 次

如何定时执行一个函数。。。希望给详细的代码。。谢谢。。
我想写一个函数,并让他每隔5秒钟执行一次。。。。有高手能够给我源码吗。。。不要跟我说典型的多线程。。。我不知道怎么用。。。也不要叫我用GTK里面的g_timeout_add............
高手给个简单的例子,比如每秒输出一个HELLOWORLD之类的,万分感谢呀。。。

------解决方案--------------------
呵呵,,可以赚分了,给你一段,最简单的,可运行的:
#include <stdio.h>
#include <sys/time.h>
#include <signal.h>

static void sig_handler();
int main()
{
struct itimerval v;
if(signal(SIGALRM, sig_handler) == SIG_ERR) {
printf( "error in create the signal \n ");
exit(0);
}
// set the interval time
v.it_interval.tv_sec = 5; // here you can change the interval time
v.it_interval.tv_usec = 0;

//set the current time
v.it_value.tv_sec = 5;
v.it_value.tv_usec = 0;

setitimer(ITIMER_REAL, &v , NULL);
while(1){};
return 1;
}

static void sig_handler()
{
printf( "time coming............!\n ");
}
------解决方案--------------------
Server:: Server(QWidget *parent) : QWidget(parent)
{
readTimer = new QTimer(this); //创建并启动定时器
connect(readTimer, SIGNAL(timeout()), this, SLOT(slotCout())); //每当定时器超时时调用函数slotCout输出“HELLOWORLD”
readTimer-> start(5000); //定时5S
}
int Server::slotCout() // 消息读取和处理函数
{
readTimer-> stop(); //暂时停止定时器计时
cout < < "HELLOWORLD " < <endl;
readTimer-> start(5000); //重新启动定时器
}
记得散分阿,穷死了
------解决方案--------------------
如何在Linux下实现定时器
如何在Linux下实现定时器

在Linux实现一个定时器,不像Win32下那样直观。在Win32调用SetTimer就行了,在Linux下则没有相应函数可以直接调用。定时器作为一个常用的功能,在Linux当然也有相应实现。下面我们看看几种常用的方法。

要实现定时器功能,最土的办法实现莫过于用sleep/usleep来实现了。当然,它会阻塞当前线程,除了处理定时功能外,什么活也干不了。当然要解决这个问题不难,创建一个单独的线程来负责定时器,其它线程负责正常的任务就行了。

要实现定时器功能,最简单的办法就是ALARM信号。这种方法简单,也相应的缺陷:用信号实现效率较低; 最小精度为1秒,无法实现高精度的定义器。简单示例:
#include <stdio.h>
#include <signal.h>

static void timer(int sig)
{
if(sig == SIGALRM)
{
printf( "timer\n ");
}

return;
}

int main(int argc, char* argv[])
{
signal(SIGALRM, timer);

alarm(1);

getchar();

return 0;
}

(setitimer和alarm有类似的功能,也是通过信号来实现)

最优雅的方法是使用RTC机制。利用select函数,你可以用单线程实现定时器,同时还可以处理其它任务。简单示例:

#include <stdio.h>
#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

int main(int argc, char* argv[])
{
unsigned long i = 0;
unsigned long data = 0;
int retval = 0;
int fd = open ( "/dev/rtc ", O_RDONLY);

if(fd < 0)
{
perror( "open ");
exit(errno);
}

/*Set the freq as 4Hz*/
if(ioctl(fd, RTC_IRQP_SET, 4) < 0)
{
perror( "ioctl(RTC_IRQP_SET) ");
close(fd);
exit(errno);
}
/*Set the freq as 4Hz*/
if(ioctl(fd, RTC_IRQP_SET, 4) < 0)
{
perror( "ioctl(RTC_IRQP_SET) ");
close(fd);
exit(errno);
}

/* Enable periodic interrupts */
if