Monitoring Thread that doesn't finish in time?

What’s the best way to wait for or detect if a running thread has taken more time to run than expected? A Timer?

Ie, my desktop app launches and starts a thread to run that should only take up to 30 seconds at most. If it fails after 30 seconds the app should display an error message and then quit.

This particular app is a faceless background app with a menubar item that is intended to only show global floating windows with ‘NewsFlashes’ for our student lab users.

If it was a standard desktop app I would instead display a progress window while the thread was running and a timer to update the UI.

depends what the thread does.
maybe thread could store current time when it starts and compare in the main loop for doing work if time is too long.

Yes, I’d use a Timer, but I’d put it in the Thread subclass and have the Thread start it on Run and stop it when it finishes. The Timer action, if it fires, would raise an Event like “Overdue”. The Event could even have an optional parameter to allow you to optionally reset the Timer and methods that would let you independently control the Timer as the Thread runs.

When it raises the Event, you can take action there.

Doing it this way will make it self-contained and give you the flexibility to reuse the subclass for other purposes.

To make the thread more generic I’m thinking of using addHandler for the thread’s .run event.

That should work, right?

yes, of course.
But the problem is always exiting a thread clean. Killing is never good.

Yep, understood. Kill threads = bad stuff.

I’d have the thread stop doing what it’s doing and clean up if the timeout was reached versus killing the thread.

I’m not sure about “never”. It’s not writing to files or the like, I can’t see how it matters if you kill it. In RegExRX, a new match starts in a thread as soon as you change the pattern. If a match is already in progress, the existing Thread is killed and new one starts. No harm.

The trick is to make sure the Thread is really dead after issuing Kill. Check the status in a loop before proceeding with any code that relies on the Thread being dead.