c_中timer控件的使用

合集下载

详解C#中的System.Timers.Timer定时器的使用和定时自动清理内存应用

详解C#中的System.Timers.Timer定时器的使用和定时自动清理内存应用

详解C#中的System.Timers.Timer定时器的使⽤和定时⾃动清理内存应⽤项⽬⽐较⼤有时候会⽐较卡,虽然有GC⾃动清理机制,但是还是有不尽⼈意的地⽅。

所以尝试在项⽬启动⽂件中,⼿动写了⼀个定时器,定时清理内存,加快项⽬运⾏速度。

public class Program{[DllImport("psapi.dll")]static extern int EmptyWorkingSet(IntPtr hwProc); //清理内存相关static void Main(){//启动定时清理内存SetTimer();}/// <summary>/// 定时清理内存/// </summary>private static void SetTimer(){System.Timers.Timer aTimer = new System.Timers.Timer(); //初始化定时器aTimer.Interval = 60000;//配置时间1分钟aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);aTimer.AutoReset = true;//每到指定时间Elapsed事件是到时间就触发aTimer.Enabled = true; //指⽰ Timer 是否应引发 Elapsed 事件。

}//定时器触发的处理事件private static void OnTimedEvent(Object source, ElapsedEventArgs e){//清理内存GC.Collect();GC.WaitForPendingFinalizers();Process[] processes = Process.GetProcesses();foreach (Process process in processes){//以下系统进程没有权限,所以跳过,防⽌出错影响效率。

timer的用法

timer的用法

Timer的用法Timer的用法主要包括以下几个方面:1.schedule方法:这是Timer类中最重要的方法之一,用于在指定的时间后执行一个任务。

它接受两个参数:第一个参数是要执行的任务,通常是一个TimerTask 对象;第二个参数是延迟时间,以毫秒为单位。

例如,以下代码会在2000毫秒后执行指定的任务:java复制代码Timer timer = new Timer();TimerTask task = new MyTask();long delay = 2000;timer.schedule(task, delay);2.scheduleAtFixedRate方法:这个方法用于定期执行一个任务。

它接受三个参数:第一个参数是要执行的任务;第二个参数是首次执行的延迟时间;第三个参数是两次执行之间的间隔时间。

例如,以下代码会每隔2000毫秒执行一次指定的任务:java复制代码Timer timer = new Timer();TimerTask task = new MyTask();long delay = 2000;long period = 2000;timer.scheduleAtFixedRate(task, delay, period);3.cancel方法:这个方法用于取消所有已安排的任务。

调用这个方法后,所有已安排的任务将不再执行。

例如,以下代码将取消所有已安排的任务:java复制代码timer.cancel();以上就是Timer的主要用法。

需要注意的是,Timer并不保证任务的执行顺序,如果需要按照特定顺序执行任务,应该使用ScheduledExecutorService等更高级的并发工具。

c中timer的用法

c中timer的用法

c中timer的用法
1. clock(函数:
示例代码:
```
#include <stdio.h>
int mai
clock_t t;
int i;
t = clock(;
//程序执行的代码
}
t = clock( - t;
return 0;
}
```
在上面的示例中,程序会测量for循环的执行时间,并将结果打印在屏幕上。

在计算程序执行时间时,需要将时钟周期转换为秒,可以通过“CLOCKS_PER_SEC”宏实现。

示例代码:
```
#include <stdio.h>
int mai
return 0;
}
```
在上面的示例中,程序将打印出当前系统时间。

除了上述基本的定时器函数之外,还有其他一些函数和方法可用于测量和处理时间:
- sleep(函数:可以让程序暂停指定的秒数。

-使用时钟频率:通过计算指令执行的时间来测量程序的执行时间。

- 使用操作系统提供的工具和库:大多数操作系统都提供了用于测量程序执行时间的工具和库,例如Windows的QueryPerformanceCounter(函数、Linu某的getrusage(函数等。

总而言之,定时器是一个在C语言中测量程序执行时间和跟踪性能的重要工具。

与操作系统提供的其他工具和库相结合,我们可以更准确地衡量我们的程序的性能,并优化我们的代码。

希望这篇文章对你理解C语言中定时器的相关用法有所帮助!。

timer_settime使用方法

timer_settime使用方法

timer_settime使用方法`timer_settime` 是一个在 POSIX 操作系统中用于设置定时器的函数。

这个函数允许你设置一个定时器,当定时器到达指定的时间时,它会产生一个信号或调用一个指定的回调函数。

下面是 `timer_settime` 函数的原型:```cint timer_settime(timer_t timerid, int flags, const struct itimerspec new_value, struct itimerspec old_value);```参数说明:`timerid`:这是由 `timer_create` 函数返回的定时器标识符。

`flags`:这个参数用于控制函数的操作方式。

通常设置为 0,除非有特定的需求。

`new_value`:指向一个 `itimerspec` 结构的指针,该结构指定了新的定时器时间值。

`old_value`:指向一个 `itimerspec` 结构的指针,该结构用于存储旧的定时器时间值。

如果不需要旧的定时器时间值,可以设置为 NULL。

`itimerspec` 结构定义如下:```cstruct itimerspec {struct timespec it_interval; // 下一个间隔时间struct timespec it_value; // 首次到期时间};```使用示例:下面是一个简单的示例,演示如何使用 `timer_settime` 函数设置一个定时器,使其在 5 秒后触发一次,然后每 2 秒触发一次:```cinclude <>include <>include <>include <>include <sys/>include <>void timer_handler(int sig) {printf("Timer expired!\n");}int main() {timer_t timerid;struct sigaction sa;struct itimerspec its;struct timeval tv;int ret;// 设置信号处理函数_flags = SA_SIGINFO;_sigaction = timer_handler;sigemptyset(&_mask);if (sigaction(SIGRTMIN, &sa, NULL) == -1) {perror("sigaction");exit(EXIT_FAILURE);}// 创建定时器timerid = timer_create(CLOCK_REALTIME, NULL, &timerid); if (timerid == (timer_t)-1) {perror("timer_create");exit(EXIT_FAILURE);}// 设置定时器时间值__sec = __sec = 2; // 首次到期时间为 2 秒,之后每 2 秒触发一次 __nsec = __nsec = 0; // 纳秒部分设置为 0ret = timer_settime(timerid, 0, &its, NULL);if (ret == -1) {perror("timer_settime");exit(EXIT_FAILURE);}// 主循环,等待信号处理函数被调用pause(); // 或者使用其他方式等待信号处理函数被调用,例如使用信号量或条件变量等机制。

VC环境下C语言定时器的使用

VC环境下C语言定时器的使用

VC环境下C语言定时器的使用当前的rae终端软件是用vc开发的,源文件中既有C++又有C。

C++的定时器使用SetTimer,该定时器需要消息机制来触发;C中的定时器依赖于不同的操作系统(多数C语言编译器不支持多线程,而且ANSI C也没有线程库,因此C语言无法实现实际意义上的定时器(即包含触发机制的定时器)),在vxworks中可用watchdog,而在windows下,SetTimer的使用依赖于消息循环,因此最好使用自定义的timer。

在自己所了解的C语言软件框架中,都使用了自定义的timer。

例如,7号信令,trillium中都是在一个独立的线程中处理与定时有关的操作。

当定时器超时,根据指针函数调用相应的回调函数。

以下所列为从网上摘抄的简单例子。

timer.h#ifndef __TIMER_H__#define __TIMER_H__typedef void (*timer_callback)(void *);typedef struct timer * timer;#define TIMER_INACTIVE 0x00000000UL#define TIMER_ACTIVE 0x00000001ULunsigned long timer_init( void );timer timer_create( const char * name, timer_callbackcb, void * param, unsigned long ticks, unsigned long remain, unsigned long status );void timer_del( timer *tp );unsigned long timer_task_del( void );#endif /*__TIMER_H__*/timer.c#include <windows.h>#include "timer.h"struct timer {struct timer * next;struct timer * prev;LPCSTR timer_name;LPVOID timer_param;ULONG timer_id;ULONG timer_counts;ULONG timer_remain;ULONG timer_status;timer_callback tcb;};static timer timer_head = NULL;static HANDLE hTimer = 0;static DWORD dwTimer = 0;static BOOL flag = TRUE;#define INT_DISABLE#define INT_ENABLEstatic timer timer_find( timer tp ){timer p = timer_head;timer rp = NULL;while ( p ) {if ( p->next == tp ) { rp = p;break;}p = p->next;}return rp;}static void timer_add( timer tp ){timer p = timer_find( NULL );if ( p == NULL ){timer_head = tp;return;}else{p->next = tp;p->next->prev = p;}}void timer_del( timer *tp ){timer p = *tp;if ( ( tp == NULL ) || ( *tp == NULL ) ) {return;}if ( p->prev ) {p->prev->next = p->next;}else {timer_head = p->next;}if ( p->next ) {p->next->prev = p->prev;}free( p );*tp = NULL;}DWORD WINAPI timer_task( LPVOID param ){timer p = NULL;while ( flag ) {Sleep( 10 );p = timer_head;while ( p ) {if ( ( p->timer_status & TIMER_ACTIVE ) && ( !--p->timer_remain ) ) {p->timer_remain = p->timer_counts;(p->tcb)(p->timer_param);}p = p->next;}}return 0;}unsigned long timer_init( void ){hTimer = CreateThread( NULL, 0, timer_task, NULL, 0, &dwTimer );if ( hTimer == NULL ) {return 0;}return 1;}unsigned long timer_task_del( void ){timer p = NULL;timer tp = NULL;if ( hTimer != NULL ) {flag = FALSE;WaitForSingleObject( hTimer, INFINITE ); CloseHandle( hTimer );hTimer = NULL;dwTimer = 0;}p = timer_head;while ( p ) {tp = p->next;free( p );p = tp;}timer_head = NULL;return 1;}timer timer_create( const char * name, timer_callbackcb, void * param, unsigned long ticks, unsigned long remain, unsigned long status ){timer p = NULL;p = malloc( sizeof( struct timer ) ); if ( p != NULL ) {p->next = NULL;p->prev = NULL;p->tcb = cb;p->timer_param = param;p->timer_counts = ticks;p->timer_remain = remain;p->timer_status = status;p->timer_name = name;timer_add( p );}return p;}test.c#include <windows.h>#include <stdio.h>#include "timer.h"void ctimer_expire( void * p ){printf( "ctimer_expire\n" );}void ptimer_expire( void * p ){printf( "ptimer_expire\n" );}void ttimer_expire( void * p ){printf( "ttimer_expire\n" );}void main(){timer ctimer = NULL;timer ptimer = NULL;timer ttimer = NULL;timer_init();ctimer = timer_create( "ctimer_expire", ctimer_expi re, NULL, 100, 100, TIMER_ACTIVE );ptimer = timer_create( "ptimer_expire", ptimer_expi re, NULL, 30, 30, TIMER_ACTIVE );ttimer = timer_create( "ttimer_expire", ttimer_expi re, NULL, 20, 20, TIMER_ACTIVE );while ( 1 ){Sleep(1000);}timer_task_del();}以下为依赖于消息机制的SetTimer的用法:#include <windows.h>#include <iostream>using namespace std;const UINT uiTimerID = 10;VOID CALLBACK FooTimerFun( HWND, UINT, UINT, DWORD ){static int nCount = 0;cout << "Timer Function , nCount = " << nCount ++ << endl;if( nCount > 5 )PostQuitMessage(0);}int main(){MSG msg;SetTimer(NULL, uiTimerID, 1000, FooTimerFun);while (GetMessage(&msg, NULL, 0, 0)){TranslateMessage(&msg); DispatchMessage(&msg); }KillTimer(NULL, uiTimerID);return 0;}特别声明:1:资料来源于互联网,版权归属原作者2:资料内容属于网络意见,与本账号立场无关3:如有侵权,请告知,立即删除。

定时器Timer

定时器Timer

首页 »软件开发 » VS2010/MFC编程入门之四十四(MFC常用类:定时器Timer)VS2010/MFC编程入门之四十四(MFC常用类:定时器Timer)分类标签: 编程入门VS2010VC++MFC前面一节鸡啄米讲了CTime类和CTimeSpan类的使用,本节继续讲与时间有关的定时器。

定时器并不是一个类,主要考虑到,提起时间的话就不能不说定时器,所以就把它放到CTime和CTimeSpan之后讲解。

定时器简介定时器,可以帮助开发者或者用户定时完成某项任务。

在使用定时器时,我们可以给系统传入一个时间间隔数据,然后系统就会在每个此时间间隔后触发定时处理程序,实现周期性的自动操作。

例如,我们可以在数据采集系统中,为定时器设置定时采集时间间隔为1个小时,那么每隔1个小时系统就会采集一次数据,这样就可以在无人操作的情况下准确的进行操作。

MFC定时器VS2010编程中,我们可以使用MFC的CWnd类提供的成员函数SetTimer实现定时器功能,也可以使用Windows API函数SetTimer来实现。

两者使用方法实际上很类似,但也有不同。

CWnd类的SetTimer成员函数只能在CWnd类或其派生类中调用,而API函数SetTi mer则没有这个限制,这是一个很重要的区别。

因为本教程主要是讲解MFC编程,所以这里就先重点讲解MFC定时器的用法,关于API函数SetTimer的用法鸡啄米会在MFC定时器讲解的基础上进行延伸。

鸡啄米下面分步骤给出使用MFC定时器的方法。

1、启动定时器。

启动定时器就需要使用CWnd类的成员函数SetTimer。

CWnd::SetTimer的原型如下:UINT_PTR SetTimer(UINT_PTR nIDEvent,UINT nElapse,void (CALLBACK* lpfnTimer)(HWND,UINT,UINT_PTR,DWORD));参数nIDEvent指定一个非零的定时器ID;参数nElapse指定间隔时间,单位为毫秒;参数lpfnTimer指定一个回调函数的地址,如果该参数为NULL,则WM_TIMER消息被发送到应用程序的消息队列,并被CWnd对象处理。

Timer 控件

Timer 控件

在 Windows 应用程序中常常要用到时间控制的功能,如在程序界面上显示当前时间,或者每隔多长时间触发一个事件,等等.而 Visual Basic 中的 Timer(时间)控制器就是专门解决这方面问题的控件.Timer 控制器在工具箱面板上的图标如图一:图一选中时钟控制器,将鼠标移到界面设计区,在窗体中拖出一个矩形就可以创建一个 Timer 控件了.跟其他控件不同的是,无论你绘制的矩形有多大,Timer 控件的大小都不会变,如图二:图二另外,Timer 控件只有在程序设计过程中看得见,在程序运行时是看不见的.一、Timer 控件的属性:Timer 控件可以使用 Name 属性与 Enabled 属性,但最重要的是 Interval 即时间间隔属性.Interval 属性决定了时钟事件之间的间隔,以毫秒为单位,取值范围为 0 ~ 65535 ,因此其最大时间间隔不能超过 65 秒,即一分钟多一点的时间.如果把 Interval 属性设置为1000 ,则表示每秒钟触发一个 Timer 事件.其语法格式:Timer.Interval = X ,其中,X 代表具体的时间间隔.二、Timer 控件的 Timer (定时)事件:当一个 Timer 控件经过预定的时间间隔,将激发计时器的 Timer 事件.使用 Timer 事件可以完成许多实用功能,如显示系统时钟、制作动画,等等.三、示例:有如图三这样一个应用程序,标签能够自动显示当前时间.图三1、创建程序界面:界面如图四,为了便于大家观看,我们将 LblShow 的边界类型设为 1 . 另外,别忘了把 Timer1 的 Interval 属性设置为 1000 .图四2、在 Timer1 的 Timer 事件中输入以下代码:Private Sub Timer1_Timer()LblShow.FontSize = 30LblShow.FontName = "宋体"LblShow.Caption = "当前时间为:" & TimeEnd Sub注意,Time 是 Visual Basic 中的关键詞,表示显示系统时间.。

winform system.threading.timer 用法

winform system.threading.timer 用法

winform system.threading.timer 用法System.Threading.Timer 是 .NET Framework 中用于实现定时任务的一个类。

在 WinForms 中,我们经常使用 Timer 控件来实现定时功能,但其实 Timer 控件底层也是使用了 System.Threading.Timer类来实现的。

本文将详细介绍 System.Threading.Timer 的用法。

一、Timer 类概述Timer 类是一个抽象类,用于创建定时器对象。

它提供了两种类型的计时器:1. 间隔定时器:定时器对象在指定的时间间隔后触发一次事件。

2. 重复定时器:定时器对象在指定的时间间隔后触发事件,并重复执行直到取消。

1. 创建 Timer 对象要使用 System.Threading.Timer 类,首先需要创建一个继承自Timer 类的新类,并实现 OnTimer 方法来处理定时器触发的事件。

然后,使用 Timer 的实例化方法来创建 Timer 对象。

示例代码:```csharppublic class MyTimer : Timer{private object _lock = new object();private Action _callback;public MyTimer(Action callback) : base() // 使用空参构造方法创建 Timer 对象{_callback = callback;}protected override void OnTick(object state){lock (_lock){_callback?.Invoke(); // 在临界区内调用回调方法}}}```在上面的示例代码中,我们创建了一个 MyTimer 类,它继承自Timer 类并重写了 OnTick 方法。

在 OnTick 方法中,我们使用 lock 语句来确保在多线程环境下回调方法的正确执行。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C#中Timer组件用法Timer组件是也是一个WinForm组件了,和其他的WinForm组件的最大区别是:Timer组件是不可见的,而其他大部分的组件都是都是可见的,可以设计的。

Timer组件也被封装在名称空间System.Windows.Forms中,其主要作用是当Timer组件启动后,每隔一个固定时间段,触发相同的事件。

Timer组件在程序设计中是一个比较常用的组件,虽然属性、事件都很少,但在有些地方使用它会产生意想不到的效果。

其实要使得程序的窗体飘动起来,其实思路是比较简单的。

首先是当加载窗体的时候,给窗体设定一个显示的初始位置。

然后通过在窗体中定义的二个Timer组件,其中一个叫Timer1,其作用是控制窗体从左往右飘动(当然如果你愿意,你也可以改为从上往下飘动,或者其他的飘动方式。

),另外一个Timer2是控制窗体从右往左飘动(同样你也可以改为其他飘动方式)。

当然这二个Timer 组件不能同时启动,在本文的程序中,是先设定Timer1组件启动的,当此Timer1启动后,每隔0.01秒,都会在触发的事件中给窗体的左上角的横坐标都加上"1",这时我们看到的结果是窗体从左往右不断移动,当移动到一定的位置后,Timer1停止。

Timer2启动,每隔0.01秒,在触发定义的事件中给窗体的左上角的横坐标都减去"1",这时我们看到的结果是窗体从右往左不断移动。

当移动到一定位置后,Timer1启动,Timer2停止,如此反覆,这样窗体也就飘动起来了。

要实现上述思路,必须解决好以下问题。

(1).如何设定窗体的初始位置:设定窗体的初始位置,是在事件Form1_Load()中进行的。

此事件是当窗体加载的时候触发的。

Form有一个DesktopLocation属性,这个属性是设定窗体的左上角的二维位置。

在程序中是通过Point结构变量来设定此属性的值,具体如下://设定窗体起初飘动的位置,位置为屏幕的坐标的(0,240)private void Form1_Load ( object sender , System.EventArgs e ){Point p = new Point ( 0 , 240 ) ;this.DesktopLocation = p ;}(2). 如何实现窗体从左往右飘动:设定Timer1的Interval值为"10",就是当Timer1启动后,每隔0.01秒触发的事件是Timer1_Tick(),在这个事件中编写给窗体左上角的横坐标不断加"1"的代码,就可以了,具体如下:private void timer1_Tick(object sender, System.EventArgs e){{ //窗体的左上角横坐标随着timer1不断加一Point p = new Point ( this.DesktopLocation.X + 1 ,this.DesktopLocation.Y ) ;this.DesktopLocation = p ;if ( p.X == 550 ){timer1.Enabled = false ;timer2.Enabled = true ;}}(3). 如何实现窗体从右往左飘动:代码设计和从左往右飘动差不多,主要的区别是减"1"而不是加"1"了,具体如下://当窗体左上角位置的横坐标为-150时,timer2停止,timer1启动private void timer2_Tick(object sender, System.EventArgs e){ file://窗体的左上角横坐标随着timer2不断减一Point p = new Point ( this.DesktopLocation.X - 1 ,this.DesktopLocation.Y ) ;this.DesktopLocation = p ;if ( p.X == - 150 ){timer1.Enabled = true ;timer2.Enabled = false ;}}三.用Visual C#编写窗体飘动程序的源代码:通过上面的介绍,不难写出窗体飘动的程序源代码。

如下:using System ;using System.Drawing ;using System.Collections ;using ponentModel ;using System.Windows.Forms ;using System.Data ;namespace floatingForm{public class Form1 : Formprivate Timer timer1 ;private Timer timer2 ;private Label label1 ;private Button button1 ;private ponentModel.IContainer components ;public Form1 ( ){file://初始化窗体中的各个组件InitializeComponent ( ) ;}file://清除在程序中使用过的资源protected override void Dispose ( bool disposing ){if ( disposing ){if ( components != null ){components.Dispose ( ) ;}}base.Dispose( disposing ) ;}private void InitializeComponent ( ){ponents = new ponentModel.Container ( ) ;this.timer1 = new Timer ( ponents ) ;this.timer2 = new Timer ( ponents ) ;bel1 = new Label ( ) ;this.button1 = new Button ( ) ;this.SuspendLayout ( ) ;this.timer1.Enabled = true ;this.timer1.Interval = 10 ;this.timer1.Tick += new System.EventHandler ( this.timer1_Tick ) ;this.timer2.Enabled = false ;this.timer2.Interval = 10 ;this.timer2.Tick += new System.EventHandler ( this.timer2_Tick ) ;this.button1.Font = new Font ( "宋体" , 10 ) ;this.button1.Location = new Point ( 1 , 8 ) ; = "button1" ;this.button1.Size = new Size ( 80 , 25 ) ;this.button1.TabIndex = 0 ;this.button1.Text = "停止飘动" ;this.button1.Click += new System.EventHandler ( this.button1_Click ) ;bel1.Font = new Font ( "宋体" , 22F , FontStyle.Bold , GraphicsUnit.Point , ( ( System.Byte ) ( 0 ) ) ) ;bel1.Location = new Point ( 8 , 38 ) ; = "label1" ;bel1.Size = new Size ( 344 , 40 ) ;bel1.TabIndex = 1 ;bel1.Text = "用Visual C#做的飘动的窗体!" ;this.AutoScaleBaseSize = new Size ( 5 , 13 ) ;this.ClientSize = new Size ( 352 , 70 ) ;this.Controls.Add (bel1 ) ;this.Controls.Add (this.button1 ) ; = "Form1" ;this.Text = "用Visual C#做的飘动的窗体!";this.Load += new System.EventHandler ( this.Form1_Load ) ;this.ResumeLayout ( false ) ;}static void Main ( ){Application.Run ( new Form1 ( ) ) ;}file://设定窗体起初飘动的位置private void Form1_Load ( object sender , System.EventArgs e ){Point p = new Point ( 0 , 240 ) ;this.DesktopLocation = p ;}file://当窗体左上角位置的横坐标为550时,timer1停止,timer2启动private void timer1_Tick(object sender, System.EventArgs e){file://窗体的左上角横坐标随着timer1不断加一Point p = new Point ( this.DesktopLocation.X + 1 ,this.DesktopLocation.Y ) ;this.DesktopLocation = p ;if ( p.X == 550 ){timer1.Enabled = false ;timer2.Enabled = true ;}}file://当窗体左上角位置的横坐标为-150时,timer2停止,timer1启动private void timer2_Tick(object sender, System.EventArgs e){ file://窗体的左上角横坐标随着timer2不断减一Point p = new Point ( this.DesktopLocation.X - 1 ,this.DesktopLocation.Y ) ;this.DesktopLocation = p ;if ( p.X == - 150 ){timer1.Enabled = true ;timer2.Enabled = false ;}}file://停止所有的timerprivate void button1_Click(object sender, System.EventArgs e){timer1.Stop ( ) ;timer2.Stop ( ) ;}}}四.总结:恰到好处的使用Timer组件往往会有出其不意的效果。

相关文档
最新文档