Question

I found this post and created a class that used it to detect inactive time and it works great. I set it for one minute and after one minute I can get it to "do stuff". What I am trying to do is only do something every "x" minutes of inactive time; i.e. every 5 minutes do this if things have been inactive and do not repeat again 'til X time has elapsed.

Now, I could set my timer to fire every 5 minutes instead of every second, but I would like to be able to "reset" the count of inactive time instead. Any suggestions?

This is for using the DispatchTimer in C# and WPF.

Was it helpful?

Solution

Just create a class level variable, increment it on your timer, and reset it when you get activity. Create a timer, say tmrDelay with an increment of 10000 milliseconds, and a button, btnActivity to reset the count, and do this:

private int tickCount = 0;
private const int tick_wait = 30; 

private void tmrDelay_Tick(object sender, EventArgs e)
{ 
    tickCount++; 

    if (tickCount > tick_wait)
    {
        DoSomething();

        tickCount = 0;   
    }
}
private void btnActivity_Click(object sender, EventArgs e)
{
    tickCount = 0;
}

OTHER TIPS

It sounds like you want something like the following:

static DispatcherTimer dt = new DispatcherTimer();

static LastInput()
{
    dt.Tick += dt_Tick;
}

static void dt_Tick(object sender, EventArgs e)
{
    var timer = (DispatcherTimer)sender;
    var timeSinceInput = TimeSpan.FromTicks(GetLastInputTime());

    if (timeSinceInput < TimeSpan.FromMinutes(5))
    {
        timer.Interval = TimeSpan.FromMinutes(5) - timeSinceInput;
    }
    else
    {
        timer.Interval = TimeSpan.FromMinutes(5);
        //Do stuff here
    }
}

This will poll every 5 minutes to see if the system has been idle for 5 minutes or more. If it's been idle for less than 5 minutes it will adjust the time so that it will go off again at exactly the 5 minute mark. Obviously then if there has been activity since the timer was set it will be adjusted again so it will always aim for 5 minutes of idleness.

If you really want to reset the active time then you will actually need to trigger some activity either by moving the mouse or sending a keypress

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top