【问题标题】:.NET Scheduled Task - WqlEventQuery to execute every 30 minutes.NET 计划任务 - WqlEventQuery 每 30 分钟执行一次
【发布时间】:2019-06-01 20:21:35
【问题描述】:

我正在与 POC 合作以使用 How to Schedule a Task In .NET Framework (C#) 中提到的库。

我让代码在特定时间运行,但是如何让它每 30 分钟执行一次?

下面是我的主要方法:

static void Main(string[] args)
        {
            WqlEventQuery query = new WqlEventQuery("__InstanceModificationEvent", 
                new System.TimeSpan(0, 0, 1), 
                "TargetInstance isa 'Win32_LocalTime' AND TargetInstance.Hour=11 AND TargetInstance.Minute=08 AND TargetInstance.Second=59");

            ManagementEventWatcher watcher = new ManagementEventWatcher(query);
            watcher.EventArrived += Watcher_EventArrived;

            watcher.Start();
            System.Console.ReadLine();
        }

【问题讨论】:

    标签: c# .net scheduled-tasks console-application system.management


    【解决方案1】:

    哦,男孩,你已经进入了WQLWMI 的土地。

    Win32_LocalTime 描述了一个时间点,这就是为什么您可以将事件设置为在特定时间触发。如果您尝试使用它来描述间隔而不是时间点,那么您可以检查当前分钟是 0 还是 30。这样,您的事件会每隔一个半小时触发一次。例如,事件将在下午 6:00、下午 6:30、晚上 7:00、晚上 7:30 等触发。您可以通过检查 TargetInstance.Minute 为 0 或 60 来检查分钟,如下所示:

    WqlEventQuery query = new WqlEventQuery("__InstanceModificationEvent",
                          new System.TimeSpan(0, 0, 1),
                          "TargetInstance isa 'Win32_LocalTime' AND (TargetInstance.Minute=0 OR TargetInstance.Minute=30)");
    

    此方法也适用于其他分钟间隔,例如 15 和 45。

    但是,使用此方法的缺点是必须指定 30 分钟间隔的特定分钟数。此外,根据您执行此代码时Win32_LocalTime 的值,您的事件可能会在最初经过 30 分钟之前触发。例如,如果您在下午 6:45 执行此代码,并且您已将事件设置为在 0 分钟和 30 分钟触发,那么第一个事件将在 15 分钟后触发,而不是 30 分钟。

    要解决这个问题,您可以改用__IntervalTimerInstruction 类。它专门以间隔生成事件。您可以通过创建它的实例并设置 ManagementEventWatcher 来侦听在满足指定时间间隔后生成的 __TimerEvent 事件来使用它。

    static void Main(string[] args)
    {
        ManagementClass timerClass = new ManagementClass("__IntervalTimerInstruction");
        ManagementObject timer = timerClass.CreateInstance();
        timer["TimerId"] = "Timer1";
        timer["IntervalBetweenEvents"] = 180000000; // 30 minutes in milliseconds
        timer.Put();
    
        WqlEventQuery query = new WqlEventQuery("__TimerEvent",
             "TimerId=\"Timer1\"");
    
        ManagementEventWatcher watcher = new ManagementEventWatcher(query);
        watcher.EventArrived += Watcher_EventArrived;
    
        watcher.Start();
        Console.ReadLine();
        watcher.Stop();
    }
    
    public static void Watcher_EventArrived(object sender, EventArrivedEventArgs e)
    {
        Console.WriteLine("Event Arrived");
    }
    

    但是,请注意,使用__IntervalTimerInstruction 创建计时器被Microsoft docs 视为一种遗留技术。此外,我必须在管理员模式下运行我的 Visual Studio 实例才能运行它。

    要查看使用__IntervalTimerInstruction 设置计时器的另一个示例,请参阅here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-28
      • 2010-10-19
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多