Benz
Benz

Reputation: 289

Executing periodically tasks in Java

I created an app that sends reminder message to clients. But I would like to make it send these messages in a specific time . I have on my database the deadline and the type of messages already riten. There are 4 types of reminder messages for every client:

  1. Before 45 days from the deadline
  2. Before 30 days.
  3. Before two weeks.
  4. Before 1 day.

enter image description here

This is the error that I have now:

enter image description here

Upvotes: 2

Views: 1064

Answers (2)

Garry
Garry

Reputation: 4533

You can use Quartz Scheduler for this, you need to create Job as below

Approach 1: How to use Quartz Scheduler in Standalone java program

public class HelloJob implements Job {
    public void execute(JobExecutionContext arg0) throws JobExecutionException{
        //your code goes here for sending reminders
    }
}

And use the SimpleTrigger to run the job once on the specified time [in new Date() in below code](which you need to calculate based on expiration like 45/30/14/1 day(s) before)

Import statements:

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

try{

SchedulerFactory sf=new StdSchedulerFactory();
Scheduler sched=sf.getScheduler();

JobDetail jd = newJob(HelloJob.class)
    .withIdentity("job1", "group1")
    .build();

SimpleTrigger st = (SimpleTrigger) newTrigger()
    .withIdentity("trigger1", sched.DEFAULT_GROUP)
    .startAt(new Date())
    .withSchedule(simpleSchedule()
            .withIntervalInSeconds(10)
            .withRepeatCount(1))
    .build();

Date ft = sched.scheduleJob(jd, st);

System.out.println(jd.getKey() +
     " will run at: " + ft +  
     " and repeat: " + st.getRepeatCount() + 
     " times, every " + st.getRepeatInterval() / 1000 + " seconds");

sched.start();

}catch (SchedulerException e) {
        System.out.println("Exception: "+e.getMessage());;
}

Approach 2: How to use Quartz Scheduler in Servlets:

You'll want to add something like this to your WEB-INF/web.xml file:

<servlet>
     <servlet-name>QuartzInitializer</servlet-name>
     <display-name>Quartz Initializer Servlet</display-name>
     <servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
     <init-param>
         <param-name>config-file</param-name>
         <param-value>quartz.properties</param-value>
     </init-param>
     <init-param>
         <param-name>shutdown-on-unload</param-name>
         <param-value>true</param-value>
     </init-param>
     <init-param>
         <param-name>wait-on-shutdown</param-name>
         <param-value>true</param-value>
     </init-param>
     <init-param>
         <param-name>start-scheduler-on-load</param-name>
         <param-value>true</param-value>
     </init-param>
 </servlet>

you need a src/main/resources/quartz.properties config file for Scheduler

# Main Quartz configuration
org.quartz.scheduler.skipUpdateCheck = true
org.quartz.scheduler.instanceName = MyQuartzScheduler
org.quartz.scheduler.jobFactory.class = org.quartz.simpl.SimpleJobFactory
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5

you may retrieve the scheduler and use it in your own Servlet like this:

public class YourServlet extends HttpServlet {
    public init(ServletConfig cfg) {        
        ServletContext servletContext = cfg.getServletContext();
        StdSchedulerFactory factory = (StdSchedulerFactory) servletContext.getAttribute(QuartzFactoryServlet.QUARTZ_FACTORY_KEY);
        Scheduler quartzScheduler = factory.getScheduler("MyQuartzScheduler");
        // and continue to implement as in approach 1
    }
}

Approach 3: How to use Quartz Scheduler in Spring:

You need to create quartz-context.xml

<context:component-scan base-package="com.gs.spring" />

<!-- if you need to invoke a method on an object -->
<bean id="simpleJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject" ref="myBean" />
    <property name="targetMethod" value="sendReminder" />
</bean>

<bean id="simpleTrigger"  class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
    <property name="jobDetail" ref="simpleJobDetail" />
    <property name="repeatCount" value="0"/>
    <property name="repeatInterval" value="10"/>
</bean>

<!-- Scheduler factory bean to glue together jobDetails and triggers to Configure Quartz Scheduler -->
    <bean  class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobDetails">
            <list>
                <ref bean="simpleJobDetail" />
            </list>
        </property>

        <property name="triggers">
            <list>
                <ref bean="simpleTrigger" />
            </list>
        </property>
    </bean>

POJO task bean

package com.gs.spring;

import org.springframework.stereotype.Component;

@Component("myBean")
public class MyBean {

    public void sendReminder() {
        //send an reminder
    }

}

Upvotes: 3

Maciej Lach
Maciej Lach

Reputation: 1681

You can use Quartz to schedule a task to verify conditions every day/hour.

Quartz tutorial provides extensive examples for number of use cases.

Quartz also integrates nicely with Spring. Your recurring task implementation:

public class RecurringTask  {

    public void execute() {
        // enter code
    }
}

and Spring's bean configuration file (scheduler.xml):

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="recurringTask" class="RecurringTask" />

    <bean id="recurringJob"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="recurringTask" />
        <property name="targetMethod" value="execute" />
        <property name="concurrent" value="false" />
    </bean>

    <bean id="recurringTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="recurringJob" />
        <property name="cronExpression" value="0 */20 * * * ?" />
    </bean>

    <!-- timer factory -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="recurringTaskTrigger" />
            </list>
        </property>
    </bean>
</beans>

Application launcher:

public class App 
{
    public static void main( String[] args ) throws Exception
    {
        new ClassPathXmlApplicationContext("scheduler.xml");
    }
}

Upvotes: 2

Related Questions