读书人

终止定时器Timer

发布时间: 2013-10-30 12:56:21 作者: rapoo

停止定时器Timer


[STAThread]
static void Main(string[] args)
{
Program p = new Program();
p.DB();
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(TimeEvent);
// 设置引发时间的时间间隔 此处设置为1秒(1000毫秒)
aTimer.Interval = 1000;
aTimer.Enabled = true;
Console.ReadLine();
}

static void TimeEvent(object source, ElapsedEventArgs e)
{
// 得到 hour minute second 如果等于某个值就开始执行某个程序。
int intMinute = e.SignalTime.Minute;
int intSecond = e.SignalTime.Second;
// 定制时间; 比如 在10:30 :00 的时候执行某个函数
//int iHour = 10;
int iMinute = 0;
int iSecond = 0;
//设置 每个小时的0分钟开始执行
if (intMinute == iMinute && intSecond == iSecond)
{
Program p = new Program();
p.DB();
}
}

如何在执行定时器的方法p.DB的时候
如果出错 则停止定时器的运行 但是控制台应用程序不退出(因为我把错误输出到了控制台,我要查看 不能退出)
[解决办法]
加try catch finally保护,在finally里面停掉定时器,不过,这时需要定时器是全局的变量
[解决办法]
try
{
}
catch
{
输出到控制台
}
[解决办法]
static void TimeEvent(object source, ElapsedEventArgs e)
{
System.Timers.Timer timer=source as System.Timers.Timer timer;
// 得到 hour minute second 如果等于某个值就开始执行某个程序。
int intMinute = e.SignalTime.Minute;
int intSecond = e.SignalTime.Second;
// 定制时间; 比如 在10:30 :00 的时候执行某个函数
//int iHour = 10;
int iMinute = 0;
int iSecond = 0;
//设置 每个小时的0分钟开始执行
if (intMinute == iMinute && intSecond == iSecond)
{
Program p = new Program();
try
{
p.DB();
}
catch
{ timer.Stop(); }



}
}
[解决办法]
跟你学习了1
[解决办法]
stateTimer.Change(-1, 任意值);就可以停止
[解决办法]

[STAThread]
static void Main(string[] args)
{
Program p = new Program();
p.DB();
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(TimeEvent);
// 设置引发时间的时间间隔 此处设置为1秒(1000毫秒)
aTimer.Interval = 1000;
aTimer.Enabled = true;
Console.ReadLine();
}

static void TimeEvent(object source, ElapsedEventArgs e)
{
try{
// 得到 hour minute second 如果等于某个值就开始执行某个程序。
int intMinute = e.SignalTime.Minute;
int intSecond = e.SignalTime.Second;
// 定制时间; 比如 在10:30 :00 的时候执行某个函数
//int iHour = 10;
int iMinute = 0;
int iSecond = 0;
//设置 每个小时的0分钟开始执行
if (intMinute == iMinute && intSecond == iSecond)
{
Program p = new Program();
p.DB();
}
}catch{ aTimer.Enabled = false;}
}

读书人网 >C#

热点推荐