如何以5秒的速度运行cron触发器超出进程

时间:2016-05-07 06:08:11

标签: spring quartz-scheduler

我已经开发了一个我想要运行的工作,每隔5秒就会说,但是在某些情况下,工作完成时间可能会超过5秒。

我的情景:我想以0.00秒然后0.05,0.10开始工作..但我的下一个工作.15秒需要超过5秒才能完成工作,所以我想跳过.20秒。我想在.25秒触发下一份工作。

Scheduler sched = sf.getScheduler();
JobDetail job1 = JobBuilder.newJob(Job1.class).withIdentity("currentTime-Job-1", "group1").build();

Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("currentTime-Job-1", "group1")
        .startAt(new Date(System.currentTimeMillis()))
        .withSchedule(CronScheduleBuilder.cronSchedule("0/5 0/1 * 1/1 * ? *")).build();

sched.start();
sched.scheduleJob(job1, trigger1);`

2 个答案:

答案 0 :(得分:0)

有两种选择:

第一种是更改用于声明作业“作业1”的界面而不是Job使用“StatefulJob”。但是这种情况已被弃用。

第二个是声明你的类扩展Job,但包括以下符号:

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class implements Job Job 1 {
// You code.
}

这可确保作业仅在同一时间运行一次。因此,如果作业花费的时间超过5秒,则下次运行重叠时应该预期正在进行中(5秒后再次尝试)。

好吧,为了回应您对使用注释的示例的请求,我在之后添加了一个。

Utilizo un proyecto Java basado en maven y mi entorno es:

Java 8 (1.8.0-92)
Eclipse 4.3.1
Quartz 2.2.1

Además,tambiéninsilyologgin con:

log4j 1.2.17
slf4f 1.7.5

Archivo pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Torren-T</groupId>
  <artifactId>torren.t.es</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
   <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
       <version>1.7.5</version>
   </dependency>
   <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-log4j12</artifactId>
       <version>1.7.5</version>
   </dependency>
  </dependencies>
</project>

主要的Java类是:

主要的Java类是:

package torren.t.es;

import org.apache.log4j.Logger;
import org.quartz.Job;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;

import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.impl.StdSchedulerFactory;


public class Terremoto {
    public static final Logger LOGGER = Logger.getLogger(Terremoto.class);

    private static Scheduler scheduler = null; 

    private Terremoto() {
    }

    private static final void dormirseNSegundos(int sleepingSeconds) {
        try {
            Thread.sleep((long)sleepingSeconds * (long)1000);
        } catch (InterruptedException e) {
            LOGGER.warn("I could not sleep");
            LOGGER.warn(e);
        }
    }

    private static final void go(Class<? extends Job> myJob) {
        JobDetail job;
        final String jobName = myJob.getName();
        final String trgName = jobName + "Trigger";
        final String grpName = jobName + "Group";


        // The Job.
        job = newJob(myJob).withIdentity(myJob.getName(), jobName).build();

        // Trigger the job to run now, and then repeat every 40 seconds
        Trigger trigger = newTrigger()
              .withIdentity(trgName, grpName)
              .startNow()
                    .withSchedule(simpleSchedule()
                      .withIntervalInSeconds(5)
                      .repeatForever())            
              .build();

        // Tell quartz to schedule the job using our trigger
          try {
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            LOGGER.error("Failed initialization job");
            LOGGER.error(e);
        }
    }

    public static final void Start() {
        Start(-1, null);
    }

    public static final void Start(int sleepingSeconds) {
        Start(sleepingSeconds, null);
    }

    public static final void Start(Class<? extends Job> myJob) {
        Start(-1, myJob);
    }

    public static final void Start(int sleepingSeconds, Class<? extends Job> myJob) {
        try {
            // Grab the Scheduler instance from the Factory
            scheduler = StdSchedulerFactory.getDefaultScheduler();

            // and start
            scheduler.start();

            // Start job.
            if (myJob != null) {
                go(myJob);
            }

            // Going to sleep!
            if (0 < sleepingSeconds) {
                dormirseNSegundos(sleepingSeconds);
            }

            // Stop Scheduler.
            scheduler.shutdown();

        } catch (SchedulerException se) {
            LOGGER.error("Failed initialization scheduler");
            LOGGER.error(se);
        }
    }

    public static void main(String[] args) {
        LOGGER.info("Starting Scheduler ...");
        Start(60, TorrenTJob.class);
    }
}

带注释的工作类:

package torren.t.es;

import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class TorrenTJob implements Job {

    public static final Logger LOGGER = Logger.getLogger(TorrenTJob.class);

    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        LOGGER.info("Hello world from a TorrenTJob!");
    }
}

我得到的控制台输出是:

2016-05-08 11:23:28 INFO  Terremoto:104 - Iniciando Scheduler ...
2016-05-08 11:23:28 INFO  StdSchedulerFactory:1184 - Using default implementation for ThreadExecutor
2016-05-08 11:23:28 INFO  SchedulerSignalerImpl:61 - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2016-05-08 11:23:28 INFO  QuartzScheduler:240 - Quartz Scheduler v.2.2.1 created.
2016-05-08 11:23:28 INFO  RAMJobStore:155 - RAMJobStore initialized.
2016-05-08 11:23:28 INFO  QuartzScheduler:305 - Scheduler meta-data: Quartz Scheduler (v2.2.1) 'SchTorrenT' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 3 threads.
  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

2016-05-08 11:23:28 INFO  StdSchedulerFactory:1339 - Quartz scheduler 'SchTorrenT' initialized from default resource file in Quartz package: 'quartz.properties'
2016-05-08 11:23:28 INFO  StdSchedulerFactory:1343 - Quartz scheduler version: 2.2.1
2016-05-08 11:23:28 INFO  QuartzScheduler:575 - Scheduler SchTorrenT_$_NON_CLUSTERED started.
2016-05-08 11:23:28 INFO  TorrenTJob:17 - Hola mundo desde un Job

答案 1 :(得分:0)

我认为这确实有效。我解释一下:

作业必须每5秒跳一次,这样可以确保基于第一次运行建立的执行频率:

07 May 2016 12:12:50 IST (first time and timebase for the rest).
07 May 2016 12:12:55 IST (do not get but two seconds later)
07 May 2016 12:13:00 IST (do not get but one second later)

...

剩下的就这样了。

会发生什么事情是在常规时间运行,也就是说,如果它在5秒后没有尝试,如果不能在可能的情况下尝试,但始终遵守定义的范围。

事实是我很困惑,我真的没想过我会在5秒后尝试,但根据设定的时间,它不是。