Timer & Codeunits

Most of you properly already know the Timer functionality that exists on Navision Forms. Have you ever thought of using it on Codeunits? Some will say that this is not possible, because the Timer property does not exists. Well – it is possible to use timers on Codeunits thanks to Automations and their WithEvent property.

Let’s take a close look on how to do it.

First you have to create a new Codeunit. Remember to set the SingleInstance property to Yes. If the SingleInstance property is not set, the Codeunit will not be listening for Timer Event triggers.

Next you have to create a global variable, which is the Timer. The Timer must be defined as the automation ‘Navision Timer 1.0’.Timer. On the Timer variable, remember to set the WithEvent property to Yes. This will add two “functions” to the Codeunit.

Timer::Timer
This will be executed, every time the timer has to be executed.

Timer::Error
This will be executed in case of an error

Now we have the Timer variable defined all that now is back to do, is to set how often the Timer has to be executed. This is done with the command Timer.Interval, where the interval is in milliseconds.

Timer.Interval := 3000;

And finally you have to enable the Timer.

Timer.Enabled := TRUE;

This code should be placed in a function or directly on the OnRun trigger. The code must only be carried out the first time the Codeunit is being executed. Because the SingleInstance property is set to Yes, the OnRun trigger will only be executed once.
Example: OnRun – trigger:

IF NOT ISCLEAR(Timer) THEN
…..CLEAR(Timer);

IF ISCLEAR(Timer) THEN
…..CREATE(Timer);

Timer.Enabled := FALSE;
Timer.Interval := 3000;
Timer.Enabled := TRUE;

The Next thing to do is to add some code on the Timer::Timer trigger. Could ex. be code that is used to listen for a file, perform a SQL query etc.
If everything is in place, then save the Codeunit and simply run it. You will see that nothing is happing right away. This is because, of the code on the OnRun trigger – the only thing that is happing, is that the Codeunit is started, placed in memory and afterwards waiting for the Timer::Timer trigger to be executed.

Now wait the amount time you have specified with the Interval command, and you will see that the Timer::Timer trigger is being executed.

The Codeunit will keep on running until you close your Navision client. Alternative, you could build in a Stop function, which then will be called from the Timer::Timer trigger.

2 Comments

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.