Why does the timer have no properties, how to get the interval after initialization?

I am using System.Threading.Timer

in my windows service for nightly import routines. It looks into the database every minute for new files to be imported. Now, since the service runs all day, I want to change it so that it runs every minute at night and every fifth minute every night.

So I thought I could check the current time, between 7:00 and 10:00 we will use the value of the day interval setting, otherwise we will use the night interval.

Now to the question: why is Timer

there no property in the class that indicates the current period / interval? Then I can decide if I need to change it or not according to this value.

As a workaround, I could store it in an additional field, but I'm wondering if it is possible to get the value from the timer itself.

Please note that I am using this constructor :

//start immediately, interval is in TimeSpan, default is every minute
importTimer = new System.Threading.Timer(
    ImportTimer_Elapsed,
    null,
    TimeSpan.Zero,
    Settings.Default.ServiceInterval_Night
);

      

+3


source to share


3 answers


Why is there no property in the Timer class that indicates the current period / interval?

I'm guessing (I'm not part of the .NET implementation team, so I must assume) this is because he was using the Win32 Waiting Timer. And there is no API for getting Waiting Timer settings .

Note that if such properties exited, there would be a race condition:



  • Topic 1 reads a property and runs some business logic on it
  • Topic 2 changes property (invalid flow 1 logic)
  • Topic 1 updates the property.

while any particular use of the timer may not be affected, the general case is to serve it.

(This is even worse in Win32, but the WaitableTimer can be called and thus accessed by other processes.)

+3


source


Instead, you can use System.Timers.Timer

that provides such a property (".Intervall")



System.Threading.Timer

has no internal field with an interval value. I looked through the .net code and I saw that it is not possible to get the current period from reflection.

0


source


Don't interfere with the tick speed. Instead, your code is called after a certain number of ticks, depending on the time:

private void ImportTimer_Elapsed(object o)
{
    tickCount--;
    if (tickCount <= 0)
    {
        // do your stuff

        tickCount = Between7AMAnd10PM() ? 5 : 1;
    }
}

      

0


source







All Articles