在Java中定期执行任务

时间:2015-08-18 10:24:51

标签: java scheduled-tasks scheduledexecutorservice

我创建了一个向客户发送提醒消息的应用。但我愿意  喜欢让它在特定时间发送这些消息。      我的数据库中有截止日期和消息类型。每种都有4种类型的提醒消息  客户:

  1. 截止日期前45天
  2. 30天之前。
  3. 两周前。
  4. 前1天。
  5. enter image description here

    这是我现在的错误:

    enter image description here

2 个答案:

答案 0 :(得分:3)

您可以使用Quartz Scheduler,您需要创建如下的作业

  

方法1:如何在独立Java程序中使用Quartz Scheduler

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

使用SimpleTrigger在指定的时间[在new Date()以下代码中]运行一次作业(您需要根据到期时间计算,如之前的45/30/14/1天)

导入声明:

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());;
}
  

方法2:如何在Servlet中使用Quartz Scheduler:

您需要在WEB-INF / web.xml文件中添加以下内容:

<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>

您需要调度程序的src/main/resources/quartz.properties配置文件

# 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

您可以检索调度程序并在您自己的Servlet中使用它,如下所示:

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
    }
}
  

方法3:如何在Spring中使用Quartz Scheduler:

您需要创建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任务bean

package com.gs.spring;

import org.springframework.stereotype.Component;

@Component("myBean")
public class MyBean {

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

}

答案 1 :(得分:2)

您可以使用Quartz安排任务以每天/每小时验证条件。

Quartz tutorial提供了大量用例的示例。

Quartz还与Spring很好地集成。您的定期任务实施:

public class RecurringTask  {

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

和Spring的bean配置文件(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>

应用程序启动器:

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