user3458271
user3458271

Reputation: 660

Is there any way to interrupt or throw custom exception on ScheduledFuture Cancel method?

I am creating a java application in which I am using ScheduledExecutorService and ScheduledFuture, My scheduling is working properly but I have an small issue, If ScheduledFuture is started once,I cannot found the option to interrupt the Runnable class, throw any custom exception or call any method which will stop my current running task, ScheduledFuture will complete the tasks even if we call future.cancle(true).

public class TaskScheduler {
    public TaskScheduler() {
        future =  executor.schedule(new JobTask(), object.getStart_time().getTime() - new Date().getTime(), TimeUnit.MILLISECONDS);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //This cancel do not stop the above started future task
        System.out.println(future.cancel(true));
   }

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, new 
    ThreadFactoryBuilder().setNameFormat("Thread1").build());
    ScheduledFuture<?> future = null;


    class JobTask implements Runnable {
    
       @Override
       public void run() {
             try {
                //running job
             } catch ( Throwable t ) { 
               System.out.println(t);
             }
       }
     // Is it possible to call any method on cancel
    public void interrupt() {
       //logic, flag or throws exception?
    }
}

Inside runnable run block we can add some sample code as below:

@Override
    public void run() {
        System.out.println("Started");
        int a = 1;
        long startTime = System.currentTimeMillis();
        int number = 2;
        int count = 0;
        long sum = 0;
        while(count < 10000) {
            if(isPrimeNumber(number)) {
                sum += number;
                count++;
            }
            number++;
        }
        System.out.println(sum);
        fib2();
        long endTime = System.currentTimeMillis();
        long duration = (endTime - startTime); 
        System.out.println(duration);
    }
    
    public void primes () {
        
    }
    
    private boolean isPrimeNumber(int number) {
        for (int i=2; i<=number/2; i++) {
            if(number % i == 0) {
                return false;
            }
        }
        return true;
    }
    public int numOfDigit(BigDecimal result){
        String s = "" + result;
        return s.length();
    }
    public void fib2(){
        BigDecimal[] dig = new BigDecimal[2];
        dig[0] = BigDecimal.valueOf(0);
        dig[1] = BigDecimal.valueOf(1);
        BigDecimal result = BigDecimal.valueOf(0);
        int c = 1;//term
        while(true){
            result = dig[0].add(dig[1]);
            dig[0] = dig[1];
            dig[1] = result;
            //check if it has 1000 digits
            if(numOfDigit(result) == 1000){
                System.out.println("Term: " + ++c);
                break;
            }
            ++c;
        }
    }

Upvotes: 0

Views: 270

Answers (1)

anurag saxena
anurag saxena

Reputation: 287

ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true) is the key factor here

you can cast the executor service reference to call the method

ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1, new 
    ThreadFactoryBuilder().setNameFormat("Thread1").build());
ex.setRemoveOnCancelPolicy(true);

or create new ScheduledThreadPoolExecutor like below :

ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(1, new 
    ThreadFactoryBuilder().setNameFormat("Thread1").build());
--and now set RemoveOnCancelPolicy
ex.setRemoveOnCancelPolicy(true);

Upvotes: -1

Related Questions