Oh boy, you've entered the land of WQL and WMI.
Win32_LocalTime describes a point in time, which is why you're able to set your event to fire at a specific time. If you're trying to use it to describe an interval instead of a point in time, then you could check if the current minute is either 0 or 30. That way, your event is raised every hour and hour and a half. For example, the event would fire at 6:00 PM, 6:30 PM, 7:00 PM, 7:30 PM etc. You can check for the minutes by checking the TargetInstance.Minute
to be 0 or 60 like so:
WqlEventQuery query = new WqlEventQuery("__InstanceModificationEvent",
new System.TimeSpan(0, 0, 1),
"TargetInstance isa 'Win32_LocalTime' AND (TargetInstance.Minute=0 OR TargetInstance.Minute=30)");
This method would also work for other minute intervals as well, such as 15 and 45.
However, using this method has the drawback of having to specify specific minutes of your 30 minute interval. Also, depending on value of Win32_LocalTime
when you execute this code, your event may fire before 30 minutes have passed initially. For example, if you execute this code a 6:45 PM and you have set your event to fire at minutes 0 and 30, then the first event will fire after 15 minutes, not 30 minutes.
To get around this, you could use the __IntervalTimerInstruction class instead. It specifically generates events in intervals. You use it by creating an instance of it and setting the ManagementEventWatcher to listen for the __TimerEvent event that is generated once the specified interval is met.
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");
}
However, be aware that creating a timer using the __IntervalTimerInstruction
is considered a legacy technique by the Microsoft docs. Also, I had to run my Visual Studio instance in Administrator mode to get this to run.
To see another example of setting up a timer with __IntervalTimerInstruction
, see here.