1

I have found a solution https://stackoverflow.com/a/2759040/4730051

But it means that the task will be canceled not after the task is started execution and a minute is exceeded, but after canceller.schedule(...) is called + 1 min. So, how to adapt it for my case?

Where cancelled is

ScheduledExecutorService canceller = Executors.newSingleThreadScheduledExecutor();
Community
  • 1
  • 1
Ivan
  • 361
  • 3
  • 16
  • 1
    Schedule cancellation from the task itself, not from outside. – Fildor Jul 15 '16 at 12:34
  • There is no `canceller.schedule` in the question that you link. Please double-check your question before you post it. You don't need to adapt it, because there is only microseconds difference between the scheduling of the two tasks, so the cancellation will occur + 1 minute after the task has started execution (it may not occur within +1.00000000000 minute, but Java doesn't guarantee thread scheduling to that level of detail anyway) – Erwin Bolwidt Jul 15 '16 at 12:36
  • 2
    @ErwinBolwidt submitting a task to an Executor does not guarantee it is executed immediately. It may be queued for later execution. In that case OP seemingly wants "to start the timer" from when execution starts not when the task has been submitted. – Fildor Jul 15 '16 at 12:39
  • @Fildor in the question that OP referred to (which he shouldn't do in this way - he should copy the code to this question) the threadpool is created with a size of 2 and immediately used to schedule a thread an cancel it. In that case it's guaranteed to start right away (immediately is a too strong guarantee, but certainly within the resolution of half a second, and "+1 minute" doesn't imply a great precision) – Erwin Bolwidt Jul 15 '16 at 12:43
  • @ErwinBolwidt I agree that the referred question behaves like that. But I do on the other hand see that OP is looking to solve something else and the question is the nearest to what he needs. So - and please correct me if wrong, Ivan - in OP's requirements there seems to be the urge to enqueue more than one task and its cancellation with a possible delayed execution. If it were exactly as in the referred question, OP obviously would have found the answer to fit his needs. – Fildor Jul 15 '16 at 12:48
  • Maybe the question could use some more clarification on requirements. – Fildor Jul 15 '16 at 12:50

0 Answers0