springboot定时任务 通过elasticJob实现

一、项目中一般都会有定时任务,如何保证定时任务在集群只执行一次,可以通过elastic-job 实现定时任务分布式部署。
(1)增加elastic-job 对于配置文件的依赖

  <dependency>
            <groupId>com.dangdang</groupId>
            <artifactId>elastic-job-lite-core</artifactId>
            <version>2.1.5</version>
        </dependency>
        <dependency>
            <groupId>com.dangdang</groupId>
            <artifactId>elastic-job-lite-spring</artifactId>
            <version>2.1.5</version>
        </dependency>

2、增加xml配置文件dangdang-es-job.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"
       xmlns:reg="http://www.dangdang.com/schema/ddframe/reg"
       xmlns:job="http://www.dangdang.com/schema/ddframe/job"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.dangdang.com/schema/ddframe/reg
                        http://www.dangdang.com/schema/ddframe/reg/reg.xsd
                        http://www.dangdang.com/schema/ddframe/job
                        http://www.dangdang.com/schema/ddframe/job/job.xsd">
    <!--注册中心 -->
    <reg:zookeeper id="regCenter" server-lists="192.168.25.133:2181" namespace="dd-job"
                   base-sleep-time-milliseconds="1000" max-sleep-time-milliseconds="3000" max-retries="3" />

    <!--configure job -->
    <job:simple id="testElasticJob" class="com.yin.databaseproject.job.TimeTask" registry-center-ref="regCenter"
                cron="0/10 * * * * ?"   sharding-total-count="1" failover="true" />
</beans>

3、在启动类中增加对xml文件的加载(此处继承 SpringBootServletInitializer 是为用tomcat启动测试集群部署是否重复执行)

@SpringBootApplication
@ImportResource(locations= {"classpath:conf/dangdang-es-job.xml"})
public class DatabaseProjectApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DatabaseProjectApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(DatabaseProjectApplication.class, args);
    }

}

4、写任务执行类

public class TimeTask implements SimpleJob {
    @Override
    public void execute(ShardingContext shardingContext) {
        String jobName = shardingContext.getJobName();
        int shardingItem = shardingContext.getShardingItem();
        System.out.println(shardingItem+":::"+jobName);
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss:SSS");

        String date =formatter.format(new Date());
        System.out.println("123333"+date);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值