Hello, I need to run a program in java daily at a certain time, I found some things about timer.schedule, but I'd like to see some examples, thanks!
Hello, I need to run a program in java daily at a certain time, I found some things about timer.schedule, but I'd like to see some examples, thanks!
Web App:
public class EnviaEmail implements Job {
public void execute(JobExecutionContext context) {
System.out.println("enviando email para evisar mudanca de senha...");
// acessar api de e-mail aqui
}
}
If we want this procedure to run once a day at midnight, we'll use the Quartz API:
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
JobDetail job = new JobDetail("dispara_email", "grupo", EnviaEmail.class);
Trigger aMeiaNoite = TriggerUtils.makeDailyTrigger(0, 0);
sched.scheduleJob(job, aMeiaNoite);
sched.start();
We could also have used expressions in the cron format, using the CronTrigger, such as triggering the Job every 20 seconds:
CronTrigger trigger =
new CronTrigger("20_segundos", "grupo", "0/20 * * * * ?");
The SendEmail class will then be instantiated at midnight, and will have its execute method (JobExecutionContext context) invoked.
There are also other alternatives to Quartz itself for task scheduling. One is to subvert Hudson, using it not only as a seamless integration server, but also to manage its tasks, leveraging its features, fault log management, and UI. Or even use cron directly by triggering requests via curl or similar. In Google App Engine, for example, there is an own cron service that works similarly, firing requests for a particular URL at the scheduled time.
Source: link
Desktop application:
In the case of a desktop application you can use the OS's own task scheduler to run a jar file at a particular time. To do this you can create a .bat file by putting code similar to the one below:
javaw -Xmx200m -jar C:\Path\to\jarfile\TheJar.jar
Note that there is a path that points to the jar directory. Then this bat can be registered in the task scheduler.
To be registered, in Windows for example, follow the steps below:
Click Start > All Programs > Accessories > System Tools > Scheduled Tasks
Do one of the following:
If the program you want to run is listed, click on the program and then click Next. If you want to run a program, a script, a document or even a .bat file that is not listed, click Open, then click the directory and the file you want schedule.
Type the name of the task and then choose one of the following:
Daily Weekly Monthly Only once When the (before the user logs in) When I log in