From 16ae5145cfbcc6ced423a1b9f88b732d252bf6c1 Mon Sep 17 00:00:00 2001 From: cw2k <3834079+cw2k@users.noreply.github.com> Date: Fri, 25 Oct 2024 16:17:45 +0200 Subject: [PATCH] BugFix: Update TaskInWorkerThread.py Now it works again as intended: ''' Counter: 0 Counter: 1 Counter: 2 The task was interrupted ''' Before the output was this: ''' Counter: 0 Counter: 1 Counter: 2 [E] Script execution error: com.pnfsoftware.jeb.client.script.ScriptExecutionException: java.lang.InterruptedException [E] at java.base/java.lang.Object.wait(Native Method) [E] at java.base/java.lang.Thread.join(Thread.java:1309) [E] at com.pnfsoftware.jeb.util.concurrent.ThreadEx.get(SourceFile:88) [E] at com.pnfsoftware.jeb.rcpclient.extensions.ui.UITask.run(UITask.java:139) [E] at com.pnfsoftware.jeb.rcpclient.extensions.ui.TaskMonitorDialog$1.run(TaskMonitorDialog.java:214) [E] at java.base/java.lang.Thread.run(Thread.java:842) [E] java.lang.InterruptedException: java.lang.InterruptedException [E] Counter: 3 Counter: 4 SimpleTask Done. ''' --- scripts/TaskInWorkerThread.py | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/scripts/TaskInWorkerThread.py b/scripts/TaskInWorkerThread.py index e9ffa08..6599e99 100644 --- a/scripts/TaskInWorkerThread.py +++ b/scripts/TaskInWorkerThread.py @@ -11,16 +11,38 @@ def run(self, ctx): if not isinstance(ctx, IGraphicalClientContext): print('This script must be run within a graphical client') return - # will start a worker thread and run the task; a pop-up will be shown to provide a way to interrupt the task - ctx.executeAsync('Counting...', SimpleTask()) - print('Done.') + # will start a worker thread and run the task; + # a pop-up will be shown to provide a way to interrupt the task + try: + ctx.executeAsync('Counting...', SimpleTask()) + # under the hood com.pnfsoftware.jeb.util.concurrent.ThreadUtil.start( ) is used to launch the thread + + except (InterruptedException,KeyboardInterrupt,): + print('The task was interrupted') + + #https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Thread.html#interrupt() + #"Interrupts this thread. + # If none of the previous conditions hold then this thread's interrupt status will be set." + #BUT + # If this thread is blocked in an invocation of the wait() ... join(), ... sleep..., then + # its interrupt status will be cleared !!! + # and it will receive an InterruptedException. + + # By this we set the missing interrupted status so SimpleTask gets the signal to stop + SimpleTask.WorkerThread_crutch.interrupt() + else: + print('Done.') class SimpleTask(Runnable): def run(self): + SimpleTask.WorkerThread_crutch=Thread.currentThread() + for i in range(10): + # react to user pressing Cancel if Thread.interrupted(): print('The task was interrupted') break + print('Counter: %d' % i) time.sleep(1)