基于Spring的几种定时任务处理方法

方法一,使用java的线程框架及PostConstruct注解:

@PostConstruct
    public void doJob() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.scheduleWithFixedDelay(
                new Runnable() {
                    @Override
                    public void run() {
                        action();
                    }
                }, 0, 10, TimeUnit.SECONDS);
    }

 方法二,使用java的线程框架及spring的context配置文件(使用bean的init-method属性):

public void doJob() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.scheduleWithFixedDelay(
                new Runnable() {
                    @Override
                    public void run() {
                        action();
                    }
                }, 0, 10, TimeUnit.SECONDS);
    }
<bean id="sender" class="cn.road2f.service.impl.Sender" init-method="doJob" />

  

方法三,使用Spring的调度任务设定配置context文件

<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="sender" method="action" cron="0/10 0 0 * * ?"/>
</task:scheduled-tasks>

<task:scheduler id="myScheduler" pool-size="1"/>

相关推荐