cmahi
cmahi

Reputation: 43

Timer task to schedule multiple jobs

Please find my requirement here.I have a InvokeTimer class which invokes TimerClass for every sec/min/hour.In the runnable of TimerClass in need to execute a logic when timer is triggered for every sec i.e if its instance of stats1 and other logic if instance of stats2 if triggered for every minute,similary for an hour.Please help me.How do i do this?

public class TimerClass extends TimerTask{
    @Override
    public void run() {
    if(stats1){
        //logic
    }else if(stats2){
        //logic
    }else{
     //logic3
    }
}

public class InvokeTimer {
        TimerClass  stats1 = new TimerClass();
        TimerClass  stats2 = new TimerClass();
        TimerClass  stats3 = new TimerClass();
        Timer timer = new Timer(true);

        timer.scheduleAtFixedRate(stats1, 0, 1 * 1000);
        timer.scheduleAtFixedRate(stats2, 0, 60 * 1000);
        timer.scheduleAtFixedRate(stats3, 0, 24* 60 * 1000);
}

Upvotes: 3

Views: 1129

Answers (2)

Sumit Kumar
Sumit Kumar

Reputation: 395

You can put common functionality in base class.

Extends all your specific stats classes to base class.

Multiple if else statement clutters the code.

Why ScheduledThreadPoolExecutor is better than Timer is explained here.

Try to use ScheduledThreadPoolExecutor as it is best for your usecase.

Example.

public class ScheduleSimulator {

    public static void main(String[] args) {

        final ScheduledExecutorService executor = Executors
                .newScheduledThreadPool(3);
        executor.scheduleAtFixedRate(new Stats1("X"), 0, 1, TimeUnit.SECONDS);
        executor.scheduleAtFixedRate(new Stats2("Y"), 0, 1, TimeUnit.MINUTES);
        executor.scheduleAtFixedRate(new Stats3("Z"), 0, 1, TimeUnit.HOURS);

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

            @Override
            public void run() {
                executor.shutdownNow();

            }
        }));
    }
}

class CommonStats {
    // Common functionality.

}

class Stats1 extends CommonStats implements Runnable {
    private String name;

    public Stats1(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public void run() {
        try {
            System.out.println("Doing a task during : " + name + " - Time - "
                    + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Stats2 extends CommonStats implements Runnable {
    private String name;

    public Stats2(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public void run() {
        try {
            System.out.println("Doing a task during : " + name + " - Time - "
                    + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class Stats3 extends CommonStats implements Runnable {
    private String name;

    public Stats3(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public void run() {
        try {
            System.out.println("Doing a task during : " + name + " - Time - "
                    + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Upvotes: 0

Lord Farquaad
Lord Farquaad

Reputation: 707

Honestly, I think your best bet here might be to make your timers anonymous classes which each support a run() method. For instance, this would be a TimerClass that beeped every second:

TimerClass stats1 = new TimerClass() {
    @Override
    public void run() {
        java.awt.Toolkit.getDefaultToolkit().beep();
    }
};

Timer timer = new Timer(true);
timer.scheduleAtFixedRate(stats1, 0, 1 * 1000);

You could have one for each stats, with unique logic within each stats's method.

Checking which version of stats is running all within the same method isn't an incredibly reliable way to set things up, but if you're dead set on it, I suppose you could make your TimerClass objects instance variables, then in your if-statements say

if(this.equals(stats1))
     //logic

but I think you'd need both classes in the same .java file for TimerTask to see them. I'd stick with the former approach if I were you.

You can find more on anonymous classes here: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

Upvotes: 1

Related Questions