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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值