Use infinite loop in Service (safe to use?)

 

Hi,

Just a quick question about Service.

Is a infinite loop, as shown below, safe to use in a MetaTrader 5 Services? Or is there a better way?

Because Services do not accept any events and therefore I can't use EventSetTimer().

Thanks :)

#property service

void DoSomething()
{
  Print("DoSomething");
}

void Loop()
{
  DoSomething(); // fetch some data (for example)

  Sleep(1000 * 60); // wait one minute

  if (!IsStopped())
    Loop(); // loop again
}

void OnStart()
{
  Loop();
}
 
Yannick Deubel:

Hi,

Just a quick question about Service.

Is a infinite loop, as shown below, safe to use in a MetaTrader 5 Services? Or is there a better way?

Because Services do not accept any events and therefore I can't use EventSetTimer().

Thanks :)

I'm not very familiar with Services, but I can offer a suggestion on the structure of your code. It's not a good idea to have a function call itself unless you are intentionally creating a recursive function that eventually exits. Your Loop function never exists as long as the service is running and repeatedly calls itself. In some languages, the way you've coded this could lead to a stack overflow. Try this instead:

#property service

void DoSomething()
{
	Print("DoSomething");
}

void OnStart()
{
        while(!IsStopped())
        {
                DoSomething();
                Sleep(1000 * 60); // wait one minute
        }
}