jeudi 16 juin 2016

How could I run two of my schedulers in parallel?

I have been wanting for a long time to add schedulers to my API. So I set a class for the purpose. Here it is.

public abstract class SyncScheduler extends Scheduler {

private Thread thread = null;
private boolean repeating = false;

@Override
public synchronized void runTask() {
    thread = new Thread(this);
    thread.start();
}

@Override
public synchronized void runTaskLater(long delay) {
    thread = new Thread(this);
    try {
        Thread.sleep(delay * 1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    thread.run();
}

@Override
public synchronized void runRepeatingTask(long period) {
    thread = new Thread(this);
    repeating = true;
    while (!thread.isInterrupted()) {
        thread.run();
        try {
            Thread.sleep(period * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Override
public synchronized void cancel() {
    if (thread != null || !repeating) {
        throw new SchedulerException("Scheduler is not started or is not a repeating task!");
    } else {
        thread.interrupt();
        repeating = false;
    }
}}

Scheduler just implements Runnable. The problem is that whenever I try to create 2 or more Schedulers, the second one never starts until the first one is finished! For example if I have on Scheduler that runs every X seconds and I have another one the cancels it, the one that cancels the first one never starts! This is the problem.

How could I run two of these schedulers in parallel?

Aucun commentaire:

Enregistrer un commentaire