Quartz定时调度初试

问题

需要按天来删除15天之前的录音文件。因为web服务器容量有限,不能什么文件都一直存放吧。

思路

本来是想在linux的crontab里面配置一个定时任务执行shell脚本的。
感觉这样做回增大代码的维护难度,看到web中有quartz这个定时调度的工具,就把定时任务加在web工程中了。

quartz的使用

用的是2.2.1版本的:
Maven:

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
  </dependency>
  <dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.2.1</version>
  </dependency>   

需要把quartz配置成一个load on startup的servlet:
web.xml中:

<servlet>  
     <servlet-name>QuartzInitializer</servlet-name>  
     <servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>  
     <init-param>  
         <param-name>config-file</param-name>  
         <param-value>/schedule/quartz.properties</param-value>  
     </init-param>  
    <init-param>    
         <param-name>shutdown-on-unload</param-name>    
         <param-value>true</param-value>    
        </init-param>  
     <load-on-startup>1</load-on-startup>  
 </servlet>  

还需要quartz的配置quartz.properties,注意路径是resource下面的/schedule/quartz.properties。maven工程的资源路径默认是resource:

org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false

org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool org.quartz.threadPool.threadCount: 10 org.quartz.threadPool.threadPriority: 5 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true org.quartz.jobStore.misfireThreshold: 60000 org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin org.quartz.plugin.jobInitializer.fileNames = /schedule/jobs.xml org.quartz.plugin.jobInitializer.failOnFileNotFound = true org.quartz.plugin.jobInitializer.scanInterval = 10 org.quartz.plugin.jobInitializer.wrapInUserTransaction = false 

quartz1.6版本org.quartz.plugin.jobInitializer.class的不是这个。
还需要配置一个jobs.xml,也在resource下的/schedule/目录下:
jobs.xml:

<?xml version='1.0' encoding='utf-8'?>
<job-scheduling-data xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData http://www.quartz-scheduler.org/xml/job_scheduling_data_1_8.xsd" version="1.8">
    <schedule>
        <job>
            <name>my-very-clever-job</name>
            <group>MYJOB_GROUP</group>
            <description>The job description</description>
            <job-class>com.ebupt.UBA.web.timer.MitJob</job-class>
        </job>
        <trigger>
            <cron>
                <name>my-trigger</name>
                <group>MYTRIGGER_GROUP</group>
                <job-name>my-very-clever-job</job-name>
                <job-group>MYJOB_GROUP</job-group>
                <cron-expression>0 0 0 * * ?</cron-expression>
            </cron>
        </trigger>
    </schedule>
</job-scheduling-data>

cron表达式表示每天0点执行。

代码

写一个任务类(定时删除15天前的wav文件):

public class MitJob implements Job {

    static Logger logger = Logger.getLogger(MitJob.class);

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        // TODO Auto-generated method stub

        InputStream inputStream = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream("application.properties");
        Properties props = new Properties();

        try {
            props.load(inputStream);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar c = Calendar.getInstance();  
        c.add(Calendar.DATE, - 15);  
        Date fifAgo = c.getTime();
        String fifAgoDate = sdf.format(fifAgo);
        logger.info("Hello! This is robin hood! The 15 days ago date is : " + fifAgoDate);
        String localPath = props.getProperty("ftp.voice.localPath.voice");
        File file = new File(localPath);
        File[] allFiles = file.listFiles();

        String fitAgoWav = fifAgoDate + ".wav";
        if (allFiles != null) {
            for (File f : allFiles) {
                String fileName = f.getName();
                String [] fileInfo = fileName.split("_");
                if (fileInfo.length != 0 && fileInfo[fileInfo.length - 1].indexOf(".wav") != -1 && fileInfo[fileInfo.length - 1].compareTo(fitAgoWav) <= 0) {
                    f.delete();
                }
            }
        }
    }

}

cron表达式

每月第一天,每隔15天,0点执行一次

<cron-expression>0 0 0 1/15 * ?</cron-expression>

你可能感兴趣的:(Quartz定时调度初试)