在 Windows 中定期运行 .NET 组件的解决方案
我需要编写一些定期运行的 .NET 代码,以检查数据库表中的“未处理”项目,处理它们,然后将它们处理后写回数据库。我们可能会将其设置为每分钟运行一次。
如何在 Windows Server 环境中的组件中进行设置,以便定期执行代码?
I need to write some .NET code that runs on a regular interval to check for "unprocessed" items in a table in the database, processes them, and then writes back to the database that they are processed. We'll probably set it up to run every minute.
How can I set up in the component in a Windows Server environment so that the code executes on a periodic basis?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Windows 服务中使用 System.Timers.Timer 。
您可以在 Windows 服务 OnStart 事件中包含这样的代码(来自 MSDN):
如果间隔不频繁,例如每天运行,也可以考虑使用 Windows 任务计划程序。它可以在给定的时间间隔内运行您的应用程序(请注意该时间间隔是否不如此频繁)。
Use System.Timers.Timer in your windows service.
You can have such a code (from MSDN) in your windows service OnStart event :
If the interval is not frequent for example if it runs daily also consider using Windows Task Scheduler. It can run your application for the given interval (note if that interval is not so frequent).
通过 Windows 任务计划程序创建计划任务。然后,计划任务将定期运行编译的 .NET EXE(我假设它是一个 EXE)。如果您需要它运行时间短于一分钟,我认为您需要迁移到 Windows 服务。
Create a scheduled task through the Windows Task Scheduler. The scheduled task would then run your compiled .NET EXE (I'm assuming it's an EXE) on a periodic basis. If you need it to run shorter than a minute, I think you then need to move to a windows service.
Windows 计划任务(启动-程序-附件-系统工具)... SSIS 作业调度... 3rd 方作业软件(Activebatch 等)...
Windows Scheduled Tasks (start-programs-accessories-system tools)... SSIS Job Scheduling... 3rd Party Job Software (Activebatch, etc)...
您可以将其设置为带有计时器的服务,该计时器会在您需要时启动(对于此频率,可能是您的最佳选择),或者您可以在 Windows Scheduler 中设置计划任务。
如果您要使用 Windows 服务路由,您的 Start() 方法将类似于:
然后您将有一个事件处理程序来处理计时器的事件(现在不记得名称了:可能是 Tick?)将调用您的实际代码。
如果您的代码需要超过一分钟才能完成,您可以将自动重新启动设置为 false,然后在处理部分将控制权交还给服务时重新启用计时器。
You can either set it up as a service with a timer which goes off whenever you want (for this frequency, probably your best option) or you can set up a scheduled task in Windows Scheduler.
If you're going with the windows service route, your Start() method will look something like:
Then you'll have an event handler to handle the Timer's event (can't remember the name right now: Tick, maybe?) which will call your actual code.
If your code takes longer than a minute to complete, you might set auto-restart to
false
and then re-enable your timer when the processing protion hands control back to the service.