如何将C#中的定时器改为24小时制?
答案:2 悬赏:0 手机版
解决时间 2021-03-07 18:38
- 提问者网友:我一贱你就笑
- 2021-03-07 14:47
如何将C#中的定时器改为24小时制?
最佳答案
- 五星知识达人网友:时间的尘埃
- 2021-03-07 15:15
using System;
namespace ConsoleApplication4
{
// 重新封装System.Timers.Timer
public class MyTimer : System.Timers.Timer
{
///
/// 获取或设置定时间隔。设置的格式如下:
///MyTimer.Interval = "20:30:15"
///
public new string Interval
{
get
{
TimeSpan ts;
double v = base.Interval;
ts = new TimeSpan((long)(v * 10 * 1000));
return ts.ToString();
}
set
{
TimeSpan ts = TimeSpan.Parse(value);
double v = ts.TotalMilliseconds;
base.Interval = v;
}
}
}
class Program
{
static void Main(string[] args)
{
// 测试 MyTimer
MyTimer timer = new MyTimer();
// 设置定时间隔为5秒
timer.Interval = "00:00:05";
timer.Elapsed += timer_Elapsed;
timer.Start();
Console.ReadLine();
timer.Stop();
}
static void timer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
MyTimer t = sender as MyTimer;
Console.WriteLine(t.Interval);
}
}
}
namespace ConsoleApplication4
{
// 重新封装System.Timers.Timer
public class MyTimer : System.Timers.Timer
{
///
/// 获取或设置定时间隔。设置的格式如下:
///
///
public new string Interval
{
get
{
TimeSpan ts;
double v = base.Interval;
ts = new TimeSpan((long)(v * 10 * 1000));
return ts.ToString();
}
set
{
TimeSpan ts = TimeSpan.Parse(value);
double v = ts.TotalMilliseconds;
base.Interval = v;
}
}
}
class Program
{
static void Main(string[] args)
{
// 测试 MyTimer
MyTimer timer = new MyTimer();
// 设置定时间隔为5秒
timer.Interval = "00:00:05";
timer.Elapsed += timer_Elapsed;
timer.Start();
Console.ReadLine();
timer.Stop();
}
static void timer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
MyTimer t = sender as MyTimer;
Console.WriteLine(t.Interval);
}
}
}
全部回答
- 1楼网友:蓝房子
- 2021-03-07 15:27
比较稳妥的做法是:设置一个比较小的时间间隔,比如1分钟,即 interval = 60000。理由是:如果你设置定时间隔为2小时,即interval=7200000,那么tick事件每2小时发生一次。假如程序运行时由于某种原因,2小时一到而没用执行tick事件处理,那你还得在等2个小时。
假设定时间隔为60000(即1分钟),代码如下:
int minutes = 0;
private void timer1_tick(object sender, eventargs e)
{
//分钟数加1
minutes++;
if ((minutes >=120)
{
// 分钟数清零,准备下次查询
minutes = 0;
//在此执行你的查询
}
}请注意上面代码的判断条件: minutes >=120
这样写,即使程序在2小时一到而没用执行tick事件处理,但在接下来的1分钟后,依然会执行你要求的操作
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯