user2262230
user2262230

Reputation: 199

Java: Running task at different intervals

I want to run the same task periodically, but at different intervals. e.g. for (1s, 2s, 3s) method should be called after 1s, 3s, 6s, 7s and so on.

Usually I use scheduleAtFixedRate, but with the same time between calls. Thanks!

Upvotes: 2

Views: 301

Answers (4)

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16080

You can use Quartz with cron expressions like

1,3,6,7,... * * * * * *

to schedule execution on specific intervals, in this case on seconds 1, 3, 6 and 7 past every minute, hour, day, year.

Cheers

Upvotes: 0

Alkis Kalogeris
Alkis Kalogeris

Reputation: 17773

The best way is to use Quartz. But if you don't want to introduce any dependencies you could use an executor. It's newer and better than timer task. Check this example

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Task implements Runnable
{       
    private int delay = 0;

    public Task(int delay) 
    {
        this.delay = delay;
    }

    public void registerNextExecution()
    {
        ScheduledExecutorService scheduledThreadPool = Executors.newSingleThreadScheduledExecutor();
        scheduledThreadPool.schedule(this, ++delay, TimeUnit.SECONDS);
    }

    @Override
    public void run() 
    {
        System.out.println("Execution at " + new Date());
        registerNextExecution();
    }
}

I haven't tested it, but I believe it's a good starting point.

Upvotes: 0

serg10
serg10

Reputation: 32717

If your schedule can be defined as a cron expression, then you could try using quartz scheduler. Obviously it might mean adding a dependency that you don't already have, but it is a mature and well used library and it is designed specifically to execute tasks based on a more complex schedule than simply periodic.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

You can scedule task execution at 1sec rate and make the task itself to skip unwanted times

Upvotes: 1

Related Questions