如何在“以星期五上午1点”为单位指定时间,以毫秒为单位指定cron作业的Java?

时间:2013-02-12 16:50:08

标签: java time cron scheduled-tasks jobs

您好我正在尝试写一个课程来安排特定时间的工作。这是代码,

public void test(){
        Timer timer = new Timer();
        Calendar date = Calendar.getInstance();
        date.set(Calendar.HOUR,0);
        date.set(Calendar.MINUTE, 0);
        date.set(Calendar.SECOND, 2);
        date.set(Calendar.MILLISECOND,0);

        //schedule to run on 1 am every friday. 
        timer.schedule(new JobRunner(), date.getTime(),1*0*0*0);
    }

请在最后一行提供帮助,我不知道如何在那里指定时间。

谢谢

1 个答案:

答案 0 :(得分:2)

我希望这会有所帮助。

    static final long period = 7*24*60*60*1000;//one week

public void test(){
    Timer timer = new Timer();
    Calendar date = Calendar.getInstance();
    date.set(Calendar.HOUR_OF_DAY, 1);
    date.set(Calendar.MINUTE, 0);
    date.set(Calendar.SECOND, 0);
    date.set(Calendar.MILLISECOND,0);
    date.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
    //in case you run the batch before date
    if (date.before(Calendar.getInstance())) {
        date.add(Calendar.DAY_OF_YEAR, 7);
    }        

    long delay =  date.getTimeInMillis() - new Date().getTime();              
    //schedule to run on 1 am every friday. 
    timer.schedule(new JobRunner(), delay, period);              
}

问候!