java项目 定时任务执行

在项目中经常会用到执行定时任务,下面的两种是我在做项目的时候用到的两种

(1)spring task

在spring.xml中beans xmlns添加

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
<task:scheduled-tasks>
    <task:scheduled ref="timeTaskServiceImpl" method="task" cron="0 * 19 * * ?"/>
</task:scheduled-tasks>

 timeTaskServiceImpl  为你要执行的类,cron来定义您执行时间

(2)java自带的类 ScheduledExecutorService

首先我们先建一个工具类commontimer

package com.wonder.Util;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 通用定时任务
 */
public class CommonTimer {

    private final static ScheduledExecutorService scheduler;

    static {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                scheduler.shutdown();
            }
        });
    }

    private static CommonTimer instance = new CommonTimer();

    private CommonTimer() {
    }

    public static CommonTimer getInstance() {
        return instance;
    }

    /**
     * 创建并执行在给定延迟后启用的 ScheduledFuture
     *
     * @param command
     * @param delay   秒
     * @return
     */
    public ScheduledFuture<?> scheduleWithSeconds(Runnable command, long delay) {
        return scheduler.schedule(command, delay, TimeUnit.SECONDS);
    }

    /**
     * 创建并执行在给定延迟后启用的 ScheduledFuture
     *
     * @param command
     * @param delay   毫秒
     * @return
     */
    public ScheduledFuture<?> scheduleWithMilliSeconds(Runnable command, long delay) {
        return scheduler.schedule(command, delay, TimeUnit.MILLISECONDS);
    }

    /**
     * 创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在
     * initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。
     *
     * @param command
     * @param delay   秒
     * @param period  秒
     * @return
     */
    public ScheduledFuture<?> scheduleAtFixedRateWithSeconds(Runnable command, long delay, long period) {
        return scheduler.scheduleAtFixedRate(command, delay, period, TimeUnit.SECONDS);
    }

    /**
     * 创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在
     * initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。
     *
     * @param command
     * @param delay   毫秒
     * @param period  毫秒
     * @return
     */
    public ScheduledFuture<?> scheduleAtFixedRateWithMilliSeconds(Runnable command, long delay, long period) {
        return scheduler.scheduleAtFixedRate(command, delay, period, TimeUnit.MILLISECONDS);

    }
}

里面封装了几个定时执行的方法

然后建一个TimeTaskListener

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * Created by Guozhijie on 2016/9/20.
*/
@Component("timeTaskListener")
public class TimeTaskListener implements ApplicationListener<ContextRefreshedEvent> {
  @Autowired
    TimeTaskService timeTaskService;

    @Override
    public   void onApplicationEvent(ContextRefreshedEvent e){
        CommonTimer.getInstance().scheduleAtFixedRateWithSeconds(timeTaskService,1,60*1);
    }
}

 实现了 spring的 applicationListener ,即为每次在启动项目的时候,在各个service类加载完成之后,开始执行

多说一句,applicationListener 这个类,很适合 在项目启动适合将一些缓存的数据加载出来

附:TimeTaskServiceImpl类 

package com.wonder.provider;

import com.wonder.exception.ServiceException;
import com.wonder.service.TimeTaskService;
import org.springframework.stereotype.Service;

/**
 * Created by Guozhijie on 2016/9/20.
 */
@Service
public class TimeTaskServiceImpl implements TimeTaskService, Runnable {
    public void task() throws ServiceException {
        try{
            System.out.println("***********************111111");
        }catch (Exception e){
            throw e;
        }

    }
    public void run(){
          task();
    }
}

猜你喜欢

转载自guozhijie87.iteye.com/blog/2325748