Skip to content

EA Doctor rule · Environment and lifecycle

Timer started but never stopped

The EA starts a timer with EventSetTimer() but never calls EventKillTimer(), which the MQL5 reference pairs with it in OnDeinit().

Why it matters

EventSetTimer() and EventSetMillisecondTimer() start the program's timer; the MQL5 reference says to stop it with EventKillTimer(), usually in OnDeinit().

An EA is not unloaded when the chart's symbol or timeframe changes or its inputs are edited: MetaTrader calls OnDeinit() and then OnInit() again. Stopping the timer in OnDeinit() and starting it in OnInit() keeps exactly one timer, at the interval of the current inputs.

When the rule fires

EventSetTimer() or EventSetMillisecondTimer() is called and EventKillTimer() appears nowhere in the file.

When it stays quiet

EventKillTimer() is called anywhere in the file.

How to fix it

  1. Call EventKillTimer() in OnDeinit().
  2. Start the timer in OnInit() and check its return value.

Code that fires it

MQL5 · fires this rule
int OnInit()
  {
   EventSetTimer(60);
   return(INIT_SUCCEEDED);
  }

void OnTimer()
  {
   Comment("Server time: ", TimeToString(TimeCurrent(), TIME_SECONDS));
  }

Fixed code

MQL5 · fixed
int OnInit()
  {
   if(!EventSetTimer(60))
     {
      Print("EventSetTimer failed: ", GetLastError());
      return(INIT_FAILED);
     }
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   EventKillTimer();
   Comment("");
  }

void OnTimer()
  {
   Comment("Server time: ", TimeToString(TimeCurrent(), TIME_SECONDS));
  }

The fixed code shows this rule’s fix and compiles in MetaEditor for MetaTrader 5 (with CTrade trade, InpLots and InpMagic declared, as in a typical EA). Other rules may still apply to it as a fragment: check your whole EA.

More rules on environment and lifecycle

Sources

Get your EA fixed

Check a whole EA for this and 29 other mistakes with EA Doctor, free and in your browser. Or send it to us: we confirm the price in writing, then fix it.