我需要编写一个调度器类,应该每5分钟、15分钟和30分钟调用一次。
我应该如何开始处理这个调度程序?我想使用Java 7。
一种方法是知道当前的时间,然后调度计算每个定时器的差异。
是否有任何图书馆或类已经做类似的工作?
发布于 2014-11-14 09:04:53
在石英2号里,这个应该是
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("someTriggerName", "someGroup")
.withSchedule(
CronScheduleBuilder.cronSchedule("0 5,15,30 * * * ?"))
.build();这将创建一个触发器,该触发器会在一小时后的正确时间内激活。第一个字段是秒;其次是分钟;然后是小时;月份;月份;周的日期(您想要指定这些日期,因此是?)。您可以为每个条目指定多个条目,而*的意思是始终如此;因此,这是所有的日子,在5、10或15分钟零秒之后。
现在你可以创建一个石英作业了
public class MyJob implements Job
{
public void execute(JobExecutionContext context throws JobExecutionException {
// do something useful
}
}并使用此触发器对其进行调度:
Scheduler sched = new StdSchedulerFactory().getScheduler();
sched.start();
sched.scheduleJob(new MyJob(), trigger);发布于 2014-11-14 08:53:26
不要重新发明车轮,使用现有的应用程序,使用石英调度器或类似的应用程序。
发布于 2014-11-14 09:01:34
如果使用的是Spring,则可以使用@Scheduled来调度任务。
检查这里以获得状态的https://spring.io/guides/gs/scheduling-tasks/。
如果简单的周期性调度不够表达,那么可以提供一个cron表达。例如,以下内容仅在工作日每15分钟执行一次。
@Scheduled(cron="* */15 * * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}在您的情况下,您需要注意cron高速公路的*和/。
* :("all values") - used to select all values within a field. For example, "*" in the minute field means "every minute".
/ :- used to specify increments. For example, "0/15" in the seconds field means "the seconds 0, 15, 30, and 45". And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50". https://stackoverflow.com/questions/26926098
复制相似问题