I want to invoke a method from servlet when system clock reach to 12pm and that method basically send some data from database to user via Email.Please can anybody help me how i can achieve this in Java Servlet.
-
1Do you want this to happen daily at 12 PM? if yes, then you can use task scheduler in windows or crontab in *inx boxes – Pradeep Simha Feb 06 '13 at 04:24
-
Yes @PradeepSimha i want this to happen daily at 12 pm. – RizN81 Feb 06 '13 at 05:05
-
@RizN81, then you can use Quartz or in-built OS scheduler. – Pradeep Simha Feb 06 '13 at 05:06
-
@PradeepSimha thank man but can i use it in Servlet? – RizN81 Feb 06 '13 at 05:19
-
@RizN81, yes you can. Search Quartz tutorials, you will get lot of details – Pradeep Simha Feb 06 '13 at 05:20
-
1Yes you can invoke quartz schedular as back-end process. Your current thread will start the process and will proceed to further servlet task as usual. Remeber: Once JVM will shut down you have to invoke quartz again. – Rais Alam Feb 06 '13 at 05:25
2 Answers
For scheduling a Job at specific time Quartz provided best API. You can create A job according to your need and create a trigger to invoke the job at 12 PM. just take a help of below link. Quartz Scheduler Example

- 6,970
- 12
- 53
- 84
A servlet is the wrong tool for the job. It's intented to act on HTTP requests, nothing more. You want just a background task which runs once on daily basis. You can't expect from an enduser that s/he should fire a HTTP request at exactly that moment in order to trigger a "background job".
Apart from the legacy Quartz library as mentioned by many others (apparently hanging in legacy J2EE era), you can also just use the standard Java SE API provided ScheduledExecutorService
for that. This needs to be initiated by a simple ServletContextListener
like this:
@WebListener
public class Scheduler implements ServletContextListener {
private ScheduledExecutorService scheduler;
@Override
public void contextInitialized(ServletContextEvent event) {
scheduler = Executors.newSingleThreadScheduledExecutor();
long millisUntil12PM = calculateItSomehow();
scheduler.scheduleAtFixedRate(new SendEmail(), millisUntil12PM, 1, TimeUnit.DAYS);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}
}
Where the class SendEmail
look like this:
public class SendEmail implements Runnable {
@Override
public void run() {
// Do your job here.
}
}
That's all. No need to mess with a legacy 3rd party library.