COMMUNITY

Using timers from within a thread causes NoEventLoopException

Hi! Try this sample code snippet.
It seems impossible to use timers within a thread.

class TimerStartedWithinThread {
    public static function main() {
        trace("Entered main method.");

        // regular timer
        var t = new haxe.Timer( 1000*2 );
        t.run = function() {
            trace("Hello from main timer.");
        }

        // an "outthreaded" timer that causes a `NoEventLoopException`
        /*
        sys.thread.Thread.create(
            function() {
                var t = new haxe.Timer( 1000*2 );
                t.run = function() {
                    trace('Hello from sub timer.');
                }
            }
        );*/
    }
}

Is there a possibility to use timers startet from another thread?
Thank you. :slight_smile:

Hey @AlienBuchner, you want to use Thread.createWithEventLoop(), all events will be executed within that thread. You could also use haxe.MainLoop.runInMainThread() so your events will run in the main thread (and then your thread doesn’t need its own event loop)

(Maybe we can improve error reporting here!)

1 Like

Hi @haxiomic!
I was looking up an old answer in the forum and reconsidered if this feature is really required in my case and so I rearranged my code structure. But it’s very nice to know these two options and they seem to work fine! So thanks a lot!! :smiley:


(So the code now would look like this:)

class TimerStartedWithinThread {
    public static function main() {
        trace("Entered main method.");

        // regular timer
        var t = new haxe.Timer( 1000*2 );
        t.run = function() {
            trace("Hello from main timer.");
        }
        
        // option 1
        sys.thread.Thread.createWithEventLoop( // <---------- this changed
            function() {
                var t = new haxe.Timer( 1000*2 );
                t.run = function() {
                    trace('Sub timer: I have my very own event loop!');
                }
            }
        );

        // option 2
        haxe.MainLoop.runInMainThread( // <---------- this changed
            function() {
                var t = new haxe.Timer( 1000*2 );
                t.run = function() {
                    trace('Sub timer: I just use the default main event loop.');
                }
            }
        );
    }
}
1 Like

It seems that starting a new timer from a delay or timer callback also will crash, atleast with hxcpp. Im guessing this is related, but code working with 4.1.2 is now broken in 4.2… So should that count as a bug?.. :thinking:

Could you post a repro example @d0oo0p, this definitely shouldn’t crash!