C# 任务仅在时间合适时运行 - 在特定时间 [英] C# Task run only if time is right - at a certain time

查看:78
本文介绍了C# 任务仅在时间合适时运行 - 在特定时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我需要构建一个仅在特定时间运行的 c# 任务,时间将来自 SQL 数据库,并且每天可能超过 1 次.

Okay, so i need to build a c# task that will only run at a certian time, the time will come from a SQL database, and it can be more then 1 time a day.

例如,c# 任务需要在 6:00、13:00、15:00 和 19:00 运行.同时它会睡觉.

For an example, the c# task need to run at 6:00, 13:00, 15:00 and 19:00. and at the meanwhile time it will sleep.

我想只做 Task.delay(60000) 并检查然后循环运行并检查 DateTime.Now <时间.

I was thinking to just do Task.delay(60000) and check then run on a loop of times and check if DateTime.Now < time.

但这似乎会使我的计算机过载,不是吗?我无法使用 Windows 管理器,因为我的任务是在执行其他任务的 Windows 服务上.

But that seems like it will overload my computer wouldn't it? I cant use windows manager because my task is on a windows service doing other tasks.

完成此类工作的最佳方法是什么?

What is the best possible way of doing this such of work?

P.S :任务工作是获取 api 并将信息获取到数据库中.

P.S : the task job is to go for an api and get info into a Database.

非常感谢您的帮助!

推荐答案

您可以使用 任务调度程序 Windows

You can use Task scheduler Windows

Task Scheduler 可用于执行任务,例如启动一个应用程序、发送电子邮件或显示消息框.任务可以调度执行:

The Task Scheduler can be used to execute tasks such as starting an application, sending an email message, or showing a message box. Tasks can be scheduled to execute:

在特定时间.

在每天的特定时间.

您可以尝试这个来为每一天动态创建一个任务,

You can try this to create a task dynamically for each day,

   using System;
   using Microsoft.Win32.TaskScheduler;
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch your application whenever the trigger fires
         td.Actions.Add(new ExecAction("my_application.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }

您编写您的 my_application.exe 用于连接 API 和拉到数据库.接下来,配置创建的任务以调用您的应用程序.

You write your my_application.exe for connection API et pull to database. Next, config the task created to call your application.

Quartz 也是一个选项,具有更丰富的 API 来创建任务并将其保存到数据库.但我认为 Windows Scheduled 任务可能会为您提供所需的一切.

Quartz is also an option with a richer API to create a task and save it to database. But I think Windows Scheduled tasks might give you all you need.

这篇关于C# 任务仅在时间合适时运行 - 在特定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆