C#如何在给定时间内运行的代码?

编程入门 行业动态 更新时间:2024-10-12 03:19:43
本文介绍了C#如何在给定时间内运行的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

要简单地说,

我开始运行在早上我的C#程序,该程序应显示在用户的消息在下午5:45。我怎样才能做到这在C#

编辑:我问这个问题,因为我想用一个定时器是不是最好的解决方案(周期性比较当前的时间的时候,我需要运行的任务):

私人无效timerDoWork_Tick(对象发件人,EventArgs五) {如果(DateTime.Now> = _timeToDoWork) { MessageBox.Show(时间回家!); timerDoWork.Enabled = FALSE; } }

解决方案

我问这个问题,因为我想用一个定时器是不是最好的解决方案(周期性比较当前的时间,我需要运行任务的时间)

为什么呢?为什么不定时器A最好的解决办法? IMO定时器是最好的解决方案。但不是你的方式已经实现。试试以下

私人System.Threading.Timer定时器; 私人无效SetUpTimer(时间跨​​度alertTime) { DateTime的电流= DateTime.Now; 时间跨度timeToGo = alertTime - current.TimeOfDay; 如果(timeToGo< TimeSpan.Zero) {的回报;已经通过 //时间} this.timer =新System.Threading.Timer(X = GT; { this.ShowMessageToUser(); },空,timeToGo,Timeout.InfiniteTimeSpan); } 私人无效ShowMessageToUser() {如果(this.InvokeRequired) { this.Invoke(新MethodInvoker(这.ShowMessageToUser)); } ,否则 { MessageBox.Show(您的信息); } }

使用像这样

SetUpTimer(新的TimeSpan(17,45,00));

To put it simply,

I start running my C# program in the morning, and the program should show the user a message at 5:45 PM. How can I do this in C#?

Edit: I asked this question because I thought using a timer is not the best solution (comparing the current time periodically to the time I need to run the task):

private void timerDoWork_Tick(object sender, EventArgs e) { if (DateTime.Now >= _timeToDoWork) { MessageBox.Show("Time to go home!"); timerDoWork.Enabled = false; } }

解决方案

I asked this question because I thought using a timer is not the best solution (comparing the current time periodically to the time I need to run the task)

Why? why not timer a best solution? IMO timer is the best solution. but not the way you have implemented. Try the following.

private System.Threading.Timer timer; private void SetUpTimer(TimeSpan alertTime) { DateTime current = DateTime.Now; TimeSpan timeToGo = alertTime - current.TimeOfDay; if (timeToGo < TimeSpan.Zero) { return;//time already passed } this.timer = new System.Threading.Timer(x => { this.ShowMessageToUser(); }, null, timeToGo, Timeout.InfiniteTimeSpan); } private void ShowMessageToUser() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(this.ShowMessageToUser)); } else { MessageBox.Show("Your message"); } }

Use it like this

SetUpTimer(new TimeSpan(17, 45, 00));

更多推荐

C#如何在给定时间内运行的代码?

本文发布于:2023-11-30 00:00:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648038.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间内   代码   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!