Using Timer and TimerTask.
Not able to understand why is this configuration starting the task immediately on deployment (using this in a web based Spring app). It should be started at today.getTime and then must repeat every day.
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 3);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
MyTask task = new MyTask();
Timer timerJob = new Timer();
timerJob.schedule(task, today.getTime(),
TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
I think, it would be better to use CronTrigger or Trigger with 24hours repeat interval.
Example of CronTrigger:
public class CronTriggerRunner {
public static void main(String args[]) throws SchedulerException, Exception {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
JobDetail job = JobBuilder.newJob(ClassToRun.class).withIdentity("jobName", "group").build();
// Starting CronTrigger
String exp = "0 0 9 * * ?"; //trigger format, everyday at 9:00 am
Trigger trigger = TriggerBuilder.newTrigger()
.startNow()
.withSchedule(
CronScheduleBuilder.cronSchedule(exp))
.build();
// Planning job detail
scheduler.scheduleJob(job, trigger);
// starting scheduler
scheduler.start();
}
}
ClassToRun.java
public class ClassToRun implements Job {
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try{
//doSomething
}
catch(Exception e){
e.printStackTrace(System.out);
}
}
}
Everyday at 9:00 am, public void execute() function will doSomething :D
Hope this will help. Please let me know.
EDIT: You need to download and add 2 jar files. 1) quartz-2.2.1.jar 2) slf4j-api-1.6.6.jar
Related
public class CronTriggerApp {
public static void main(String[] args) {
try {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
JobDetail job = JobBuilder.newJob(Main.class)
.withIdentity("dummyJobName", "group1").build();
System.out.println(job);
Date startTime = DateBuilder.nextGivenSecondDate(null, 5);
System.out.println(startTime);
// run every 20 seconds infinite loop
CronTrigger crontrigger = TriggerBuilder
.newTrigger()
.withIdentity("TwentySec", "group1")
.startAt(startTime)
.startNow()
.withSchedule(CronScheduleBuilder.cronSchedule("* * * ? * *"))//0 53 12 * * ? *
.build();
scheduler.start();
scheduler.scheduleJob(job, crontrigger);
//scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Main implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException
{
System.out.println("Trigger Starts.."+new Date());
System.out.println("ALL_OFF");
}
}
By using above code i can able to schedule cron job..but if want cancel the schedule time how can able to cancel or stop the schedule task?
can any one plz help me how can i stop or cancel the scheduled task?
You can expose an endpoint to interrupt it. And use the following function of scheduler to stop it.
scheduler.interrupt(jobDetail.getKey());
I am new to java and trying to learn quartz. I have main method
public static void main(String[] args) throws SchedulerException {
try {
JobDetail job1 = JobBuilder.newJob(Job1.class).withIdentity("job1", "group1").build();
Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("cronTrigger1", "group1")
.withSchedule(CronScheduleBuilder.weeklyOnDayAndHourAndMinute(3, 12, 38)).build();
Scheduler scheduler1 = new StdSchedulerFactory().getScheduler();
scheduler1.start();
scheduler1.scheduleJob(job1, trigger1);
scheduler1.shutdown();
}
catch (Exception e) {
e.printStackTrace();
}
Which works fine. It prints to the console on 3rd day of the week at 12:38 pm.
Now, what I want to do is to reschedule the trigger, so that it deletes the previous stored trigger and creates a new trigger with new schedule.
I read a lot of things at a lot of places but I just can't seem to understand clearly what I actually have to do, for ex:
public void execute(JobExecutionContext context) throws JobExecutionException {
Trigger newTigger = what ever you want;
Trigger oldTrigger = context.getTrigger()
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);
}
and also this:
// Define a new Trigger
Trigger trigger = newTrigger()
.withIdentity("newTrigger", "group1")
.startNow()
.build();
// tell the scheduler to remove the old trigger with the given key, and
// put the new one in its place
sched.rescheduleJob(triggerKey("oldTrigger", "group1"), trigger);
but I can't understand the approach(I do understand what is happening in the code though). Thanks in advance.
public static void setupSchedule() {
try {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
JobDetail job = newJob(Reader.class).withIdentity("job1", "group1").build();
String Frequency = Props.getProps().getProperty("BIRTHDAYFREQUENCY");
CronTrigger ct = newTrigger().withIdentity("trigger1", "group1")
.withSchedule(cronSchedule(Frequency)).build();
scheduler.scheduleJob(job, ct);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
If you are asking to implement quartz scheduler in web application then answer is yes.
All you have to do put all scheduler configuration in servlet init method. Like you have done it your question. Init method will be called only once on start-up of application or on first request. So all the configuration and scheduler time will be set at that time. Make sure to include all the quartz dependencies.
private Scheduler scheduler ;
public void init(ServletConfig config) throws ServletException
{
JobKey jobKeyA = new JobKey("jobA", "group1");
JobDetail jobA = JobBuilder.newJob(CallJob.class)
.withIdentity(jobKeyA).build();
//jobA.getJobDataMap().put("queue_setup", queue_setup);
Trigger trigger1 = TriggerBuilder
.newTrigger()
.withIdentity("triggerJobA", "group1")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInMinutes(1).repeatForever()).build();
//runs every minute
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(jobA, trigger1);
}
Job class
public class CallJob implements Job {
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException
{
System.out.println("Yes job is running");
}
}
I would like to use Java Timer and TimerTask to do a Job everyday evening at 5 O' clock.
Please help me to solve this problem.
Problem with below methods as I think...
schedule(TimerTask task, Date time)
----Date can be specified for first day only not for forthcomingdays available.
schedule(TimerTask task, Date firstTime, long period)
----initial starting time and after how long it is to be executed can be given,
here if I start initlally my scheduler at 4 O' Clock evening then how to mention the next execution time. If I set 1 hour delay it will call after every one hour.
schedule(TimerTask task, long delay)
--This is not applicable which will do things based on start times.
schedule(TimerTask task, long delay, long period)
--This is not applicable which will do things based on start times.
I suggest you to switch to Quartz Cron Trigger which is very light and easy to use
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
//Job1 is scheduled to run everyday evening at 5 O' clock
JobDetail job = newJob(SimpleJob.class)
.withIdentity("job1", "group1")
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0 0 17 * * ?"))
.build();
sched.scheduleJob(job, trigger);
well the more appropriate answer is the one by Grooveek
but as an alternative
import java.awt.Toolkit;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class demo
{
Toolkit toolkit;
Timer timer;
public demo()
{
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new scheduleDailyTask(), 0, //initial delay
1 * 1000); //subsequent rate
}
class scheduleDailyTask extends TimerTask
{
public void run()
{
Date date = new Date();
if(date.getHours()==5 && date.getMinutes()==0 && date.getSeconds()==0)
{
System.out.println("its 5 O clock");
System.out.println("run the daily schedule method now");
}
}
}
public static void main(String args[]) {
new demo();
}
}
try
Calendar c = Calendar.getInstance();
c.clear(Calendar.MILLISECOND);
c.clear(Calendar.MINUTE);
c.clear(Calendar.SECOND);
if (c.get(Calendar.HOUR_OF_DAY) > 17) {
c.add(Calendar.DATE, 1);
}
c.set(Calendar.HOUR_OF_DAY, 17);
Date firstTime = c.getTime();
new Timer().scheduleAtFixedRate(task, firstTime, 24 * 3600 * 1000);
I'm using Quartz to write a simple server monitor in Java:
public class ServerMonitorJob implements Job {
#Override
public void execute(JobExecutionContext ctx) {
// Omitted here for brevity, but uses HttpClient to connect
// to a server and examine the response's status code.
}
}
public class ServerMonitorApp {
private ServerMonitorJob job;
public ServerMonitorApp(ServerMonitorJob jb) {
super();
this.job = jb;
}
public static void main(String[] args) {
ServerMonitorApp app = new ServerMonitorApp(new ServerMonitorJob());
app.configAndRun();
}
public void configAndRun() {
// I simply want the ServerMonitorJob to kick off once
// every 15 minutes, and can't figure out how to configure
// Quartz to do this...
// My initial attempt...
SchedulerFactory fact = new org.quartz.impl.StdSchedulerFactory();
Scheduler scheduler = fact.getScheduler();
scheduler.start();
CronTigger cronTrigger = new CronTriggerImpl();
JobDetail detail = new Job(job.getClass()); // ???
scheduler.schedule(detail, cronTrigger);
scheduler.shutdown();
}
}
I think I'm somewhere around the 70% mark; I just need help connecting the dots to get me all the way there. Thanks in advance!
You are almost there:
JobBuilder job = newJob(ServerMonitorJob.class);
TriggerBuilder trigger = newTrigger()
.withSchedule(
simpleSchedule()
.withIntervalInMinutes(15)
);
scheduler.scheduleJob(job.build(), trigger.build());
Check out the documentation, note that you don't need a CRON trigger when you simply want to run the job every 15 minutes.