-2

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.

Addict
  • 693
  • 2
  • 7
  • 16
RizN81
  • 971
  • 14
  • 23

2 Answers2

5

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

Rais Alam
  • 6,742
  • 11
  • 50
  • 84
1

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.

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452