我想定期运行相同的任务,但是时间间隔不同。 例如for(1s,2s,3s)方法应在1s,3s,6s,7s之后调用。
通常我使用scheduleAtFixedRate
,但调用之间的时间相同。谢谢!
答案 0 :(得分:1)
您可以以1秒的速率执行任务执行,并使任务本身跳过不需要的时间
答案 1 :(得分:0)
您可以使用Quartz with cron expressions之类的
1,3,6,7,... * * * * * *
按特定时间间隔安排执行,在这种情况下,在每分钟,每小时,每天,每年的第1,3,6和7秒后执行。
干杯
答案 2 :(得分:0)
如果您的日程安排可以定义为cron expression,那么可以尝试使用quartz scheduler 。显然,它可能意味着添加一个您尚未拥有的依赖项,但它是一个成熟且使用良好的库,它专门用于执行基于比简单周期更复杂的计划任务。
答案 3 :(得分:0)
最好的方法是使用Quartz。 但是,如果您不想引入任何依赖项,则可以使用执行程序。它比计时器任务更新,更好。 检查此示例
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();
}
}
我还没有测试过,但我相信这是一个很好的起点。