c# 定周期执行一个函数

概要

定周期执行一个函数。

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace 定周期函数
{
    class Program
    {
        static void Main(string[] args)
        {
            Program program = new Program();
            program.main();
            Console.ReadKey();
        }
        public void main() {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.Interval = 1000; //
            timer.Start();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(writeHead);
        }
        private void writeHead(object source, ElapsedEventArgs e)
        {
            Console.WriteLine(DateTime.Now.ToString());
        }
    }
}

运行效果 

2.补充说明

2.1 qt 定周期执行一个函数

在Qt中,如果你想要定周期执行一个函数,可以使用QTimer类。QTimer提供了重复和单次的定时器功能。以下是如何使用QTimer来定周期执行一个函数的简单示例:

  1. 创建一个QTimer对象:
QTimer *timer = new QTimer(this);
  1. 连接QTimertimeout()信号到你想要定期执行的函数:
connect(timer, &QTimer::timeout, this, &YourClass::yourFunction);
  1. 设置定时器的间隔并启动它:
timer->start(1000); // 定时器每1000毫秒(1秒)触发一次

这样,yourFunction就会每隔1秒被调用一次。

完整示例:

#include <QTimer>  
#include <QObject>  
#include <QDebug>  
  
class YourClass : public QObject {  
    Q_OBJECT  
public:  
    YourClass() {  
        QTimer *timer = new QTimer(this);  
        connect(timer, &QTimer::timeout, this, &YourClass::yourFunction);  
        timer->start(1000); // 设置定时器间隔为1000毫秒  
    }  
  
public slots:  
    void yourFunction() {  
        qDebug() << "Function is called every second.";  
    }  
};  
  
int main(int argc, char *argv[]) {  
    QCoreApplication a(argc, argv);  
    YourClass obj;  
    return a.exec();  
}  
  
#include "main.moc"

在这个示例中,YourClass有一个成员函数yourFunction,它会被定时器每隔1秒调用一次。注意,由于我们使用了QCoreApplication,这个程序是一个没有界面的控制台应用程序。如果你在一个图形界面应用程序中使用QTimer,通常你会将QTimer作为某个QWidgetQMainWindow的子对象来创建。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值