![](/img/trans.png)
[英]how can I monitor (listen) the job I scheduled with @scheduled using spring framework?
[英]using Timer class - How can I make a scheduled Job started as scheduled even if the prior job isn't finished?
在不使用Quartz的情况下,即使上一个作业没有完成,Timer类还是可以选择启动预定作业?
这是示例代码。
工作计划每1秒
public static void main(String[] args) {
Timer timer = new Timer();
Calendar date = Calendar.getInstance();
timer.scheduleAtFixedRate(new UnitTest(timer), date.getTime(), 1000);
}
工作执行
每项工作都有2秒延迟
public void run() {
count++;
int a = count; // to see which job is started and ended.
System.out.println(this.now("HH:mm:ssSSS")+"- start "+count);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
System.out.println(this.now("HH:mm:ssSSS")+"- end "+a);
}
结果 - 如果上一个作业未完成,则不会启动下一个作业。
12:14:21946 - start 1
12:14:23965 - end 1
12:14:23965 - start 2
12:14:25966 - end 2
12:14:25967 - start 3
12:14:27968 - end 3
12:14:27968 - start 4
12:14:29969 - end 4
12:14:29970 - start 5
12:14:31970 - end 5
12:14:31971 - start 6
12:14:33972 - end 6
如何为Timer类添加此选项?
Quartz -来自http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html的 并发选项
默认情况下,Quartz Jobs是无状态的,导致作业相互干扰的可能性。 如果为同一JobDetail指定两个触发器,则可能在第一个作业完成之前,第二个作业将启动。 如果JobDetail类实现Stateful接口,则不会发生这种情况。 第二个作业在第一个作业完成之前不会开始。 要使MethodInvokingJobDetailFactoryBean产生的作业非并发,请将concurrent标志设置为false。
编辑样本代码
public class TEST01 {
Timer timerTEST01 = new Timer();
public String[] start()
{
try
{
timerTEST01.scheduleAtFixedRate(new TimerTask() {
public void run() {
Runnable r = new Runnable() {
public void run() {
//DoWork
}
};
Thread t = new Thread(r);
t.start();
}
}, date.getTime(), 1000*60);
return new String[]{"true", "Good Job!"};
}
catch(Exception e){}
finally{}
}
}
当计时器调用您的方法时,不是直接在计时器上运行代码,而是生成一个新线程(或使用线程轮询)来执行您的任务:
public void run() {
Runnable r = new Runnable() {
public void run() {
count++;
int a = count; // to see which job is started and ended.
System.out.println(this.now("HH:mm:ssSSS")+"- start "+count);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
System.out.println(this.now("HH:mm:ssSSS")+"- end "+a);
}
};
Thread t = new Thread(r);
t.start();
}
这将保证每个作业在给定时间执行,即使前一个作业尚未执行。
另外,请确保您的代码在匿名内部类中运行, 计数++可能无法正常工作。
TimerTask timertask=new TimerTask(
public void run(){
//code
}
);
Timer timer = new Timer();
//Use timer to execute and set time limits for execution
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.