Working with timer

For many applied tasks, it is important to be able to perform actions on a schedule, with some specified interval. In MQL5, this functionality is provided by the timer, a system time counter that can be configured to send regular notifications to an MQL program.

There are several functions for setting or canceling timer notifications in the MQL5 API: EventSetTimer, EventSetMillisecondTimer, EventKillTimer. The notifications themselves enter the program as events of a special type: the OnTimer handler is reserved for them in the source code. This group of functions will be discussed in this chapter.

Recall that in MQL5 events can only be received by interactive programs running on charts, that is, indicators and Expert Advisors. Scripts and Services do not support any events, including those from the timer.

However, in the chapter Functions for working with time, we have already touched on related topics:

  • Getting the timestamps of the current local or server clock (TimeLocal / TimeCurrent)
  • Pausing the execution of the program for a specified period using Sleep
  • Getting the state of the computer's system time counter, counted from the start of the operating system (GetTickCount) or since the launch of MQL-program (GetMicrosecondCount)

These options are open to absolutely all types of MQL programs.

In the previous chapters, we have already used the timer functions many times, although their formal description will be given only now. Due to the fact that timer events are available only in indicators or Expert Advisors, it would be difficult to study it before the programs themselves. After we have mastered the creation of indicators, the topic of timers will become a logical continuation.

Basically, we used timers to wait for the timeseries to be built. Such examples can be found in the sections Waiting for data, Multicurrency and multitimeframe indicators, Support for multiple symbols and timeframes, Using built-in indicators.

In addition, we timed (every 5 seconds) the type of the subordinate indicator in the indicator "animation" demo in the section Deleting indicator instances.