使用Timer类 - 即使先前的作业未完成,如何使计划的作业按计划启动?

时间:2011-12-08 03:20:59

标签: java timer scheduler

不使用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类添加此选项?

来自http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

Quartz - Concurrent Option

默认情况下,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{}
}
}

2 个答案:

答案 0 :(得分:4)

当计时器调用您的方法时,不是直接在计时器上运行代码,而是生成一个新线程(或使用线程轮询)来执行您的任务:

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();
}

这将保证每个作业在给定时间执行,即使前一个作业尚未执行。

另外,请确保您的代码在匿名内部类中运行, count ++ 可能无法正常工作。

答案 1 :(得分:0)

TimerTask timertask=new TimerTask(
    public void run(){
        //code
        }
    );

Timer timer = new Timer();
//Use timer to execute and set time limits for execution