There may be an easier way but I would probably try
- writing a script that either exits/kills itself once it is finished
- write 2 scripts, one that starts the process and one that you call on the thread closing. the start script could have some logic to look if it is already running and kill any processes necessary.