定时任务(2)

定时任务注解方式:

application2.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:aop="http://www.springframework.org/schema/aop"

    xmlns:task="http://www.springframework.org/schema/task"

    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

       http://www.springframework.org/schema/beans/spring-beans.xsd

       http://www.springframework.org/schema/context

       http://www.springframework.org/schema/context/spring-context.xsd

       http://www.springframework.org/schema/aop

       http://www.springframework.org/schema/aop/spring-aop.xsd

       http://www.springframework.org/schema/task

       http://www.springframework.org/schema/task/spring-task.xsd">

    <!-- 方式二: 开启IOC注解扫描 -->

    <context:component-scan base-package="com"/>

    <!-- 配置定时任务驱动 开启这个配置,spring才能识别 @Scheduled-->

     <task:annotation-driven/>

</beans>

TaskJob2:

package com.java.task;

import java.text.SimpleDateFormat;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component

public class TaskJob2 {

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   

    //定义定时任务方法

    @Scheduled(cron="0/2 * * * * ?")

    public void job1() {

        System.out.println("定时任务1..."+sdf.format(new Date()));

    }

    @Scheduled(cron="0/5 * * * * ?")

    public void job2() {

        System.out.println("定时任务2..."+sdf.format(new Date()));

    }

}

ApplicationTest2:

package com.java.app;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.java.task.TaskJob2;

public class ApplicationTest2 {

    public static void main(String[] args) {

        ApplicationContext ac=new ClassPathXmlApplicationContext("application.xml");

        TaskJob2 job=(TaskJob2)ac.getBean("taskJob2");

   

    }

}

输出:

定时任务2...2021-06-08 19:09:55

定时任务1...2021-06-08 19:09:56

定时任务1...2021-06-08 19:09:58

定时任务2...2021-06-08 19:10:00

定时任务1...2021-06-08 19:10:00

定时任务1...2021-06-08 19:10:02

定时任务1...2021-06-08 19:10:04

定时任务2...2021-06-08 19:10:05

备注:学习笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值