34

Is it possible to crate a job that will trigger immediately ? when i want the job to be triggres now i builed a cron expression string with the current date and time - i think it's too complicated, is there another way to trigger the job immediately ?

Thank's In Advance.

STW
  • 44,917
  • 17
  • 105
  • 161
user590586
  • 2,960
  • 16
  • 63
  • 96

3 Answers3

58

Yeah, use the following Trigger to immediately fire your job instead of waiting upon the Cron Expressions.

    String jobName = ""; // Your Job Name
    String groupName = ""; // Your Job Group
    Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName, groupName)
                .startNow()
                .build();
Rohit Bansal
  • 1,199
  • 1
  • 10
  • 18
36

All the Jobs registered in the Quartz Scheduler are uniquely identified by the JobKey which is composed of a name and group . You can fire the job which has a given JobKey immediately by calling triggerJob(JobKey jobKey) of your Scheduler instance.

//Create a new Job 
JobKey jobKey = JobKey.jobKey("myNewJob", "myJobGroup");
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity(jobKey).storeDurably().build();

//Register this job to the scheduler
scheduler.addJob(job, true);

//Immediately fire the Job MyJob.class
scheduler.triggerJob(jobKey);

Note :

  • scheduler is the Scheduler instance used throughout your application . Its start() method should be already called after it is created.

  • The job is the durable job which cannot attach any triggers or cron to it .It can only be fired programmatically by calling triggerJob(JobKey jobKey).

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
  • Why not using `SimpleTrigger` and use `scheduler.scheduleJob()` which will result in immediate execution? – basZero Dec 31 '12 at 12:58
  • 2
    FYI JobKey is not part of the 1.5.2 API. – David Mann Jan 02 '14 at 20:23
  • 1
    The job has to be set durable (.storeDurably()) but then we have to clean it up manually (probably using scheduler.deleteJob()) or the job will stay persistently in the DB. I wonder how people deal with this problem? – leeyuiwah Mar 03 '14 at 22:49
  • Usually you don't want to firing the job concurrently. It is possible as you have scheduled the job, and then fire it immediately. If you are using the 2.x version, you can annotate your job class with @DisallowConcurrentExecution, but if you are using older versions, you can implement your job using the old StatefulJob interface. – Yuci May 06 '16 at 10:36
0

You can create the "JobKey" on the fly with the 2 key string values.

IScheduler sched = /* however you get your scheduler*/;

sched.TriggerJob(new JobKey("myname", "mygroup"));
granadaCoder
  • 26,328
  • 10
  • 113
  • 146