String task 定时任务

String task 定时任务

maven依赖

        <!-- Task 需要使用此依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth-zipkin</artifactId>
            <version>1.1.2.RELEASE</version>
        </dependency>

实体

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ApiModel(description = "ResTask")
public class ResTask extends SimpleGenericEntity<String> {
    @ApiModelProperty(value = "", example = "", name = "", hidden = true)
    private String id;
    @ApiModelProperty(value = "定时方式", example = "定时方式", name = "定时方式")
    private String code;
    @ApiModelProperty(value = "请求地址", example = "请求地址", name = "请求地址")
    private String url;
    @ApiModelProperty(value = "josn参数", example = "josn参数", name = "josn参数")
    private String obj;
    @ApiModelProperty(value = "请求方式", example = "请求方式", name = "请求方式")
    private String getorpost;
}

发http请求工具

@Service
public class HttpRequest {
    private Logger log = Logger.getLogger(HttpRequest.class);
    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    ResourceFeign resourceFeign;
    public String getString(String url) {
        String str = restTemplate.getForObject(url, String.class);
        return str;
    }
    String postString(String url, Object obj) {
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        Map<String, String> map = new HashMap<>();
        map.put("ContentType", "application/x-www-form-urlencoded");
        String str = restTemplate.postForObject(url, obj, String.class, map);
        return str;
    }
}

定时任务

@Slf4j
@Component
public class ScheduledService {

    @Autowired
    private HttpRequest httpRequest;

    @Autowired
    private ActivityFeign activityFeign;

    @Autowired
    private ResTaskDao httpRequestDao;

    /**
     * cron:通过表达式来配置任务执行时间
     */
    @Async
    @Scheduled(cron = "0/5 * * * * *")
    public void scheduled() {
        List<ResTask> data = httpRequestDao.getCronRate("cron");
        log.info("==>{} 每5秒执行 。", activityFeign.task());
        httpTask(data);
    }


    /**
     * cron:每天4点执行
     */
    @Async
    @Scheduled(cron = "0 0 4 * * ?")
    public void scheduled12() {
        List<ResTask> data = httpRequestDao.getCronRate("cron4");
        log.info("==>{} 4点执行", data);
        httpTask(data);
    }

    /**
     * fixedRate:指定两次任务执行的时间间隔(毫秒),
     * 此时间间隔指的是,前一个任务开始与下一个任务开始的间隔
     */
    @Async
    @Scheduled(fixedRate = 30000)
    public void scheduled1() {
        List<ResTask> data = httpRequestDao.getCronRate("fixedRate");
        httpTask(data);
        log.info("==>{} 使用fixedRate  30秒执行一次。", System.currentTimeMillis());
    }

    /**
     * fixedDelay:指定两次任务执行的时间间隔(毫秒),
     * 此时间间隔指的是,前一次任务结束与下一个任务开始的间隔
     */
    @Async
    @Scheduled(fixedDelay = 1800000)
    public void scheduled2() {
        List<ResTask> data = httpRequestDao.getCronRate("fixedDelay");
        httpTask(data);
        log.info("==>{} 使用fixedDelay半个钟执行一次。", System.currentTimeMillis());
    }

    /**
     * 发送http请求 仅支持GET and POST
     *
     * @param data 参数
     */
    private void httpTask(List<ResTask> data) {
        data.forEach(f -> {
            String s = null;
            if ("GET".equals(f.getGetorpost())) {
                s = httpRequest.getString(f.getUrl());
            } else if ("POST".equals(f.getGetorpost())) {
                s = httpRequest.postString(f.getUrl(), JSON.parse(f.getObj()));
            }
            log.info("==>{} 返回值", s);
        });
    }
}

配置文件

@Configuration
@EnableAsync
public class AsyncConfig {

    /**
     * 此处成员变量应该使用@Value从配置中读取
     */
    private int corePoolSize = 10;
    private int maxPoolSize = 200;
    private int queueCapacity = 10;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }
}

dao操作

@Component
public interface ResTaskDao extends CrudDao<ResTask, String> {

    /**
     * 查询执行任务
     * @return http请求
     */
    @Select("SELECT t.* FROM kitop_resource.res_task t  WHERE code=#{cron}")
    List<ResTask> getCronRate(String cron);
}

数据库表


create table res_task
(
    id        varchar(36)  default ''     not null
        primary key,
    code      varchar(100) default 'cron' null comment '定时方式 cron4 :没天4点执行
cron:每隔5秒执行
fixedRate:每个30秒执行
fixedDelay:半个钟执行',
    url       varchar(100)                null comment '请求地址',
    obj       text                        null comment 'josn参数',
    getOrPost varchar(100) default 'GET'  null comment '请求方式'
);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值