java实现定时任务 schedule_spring schedule的简单实现

Schedule

关于spring一个计时器功能的实现

spring 的计时器是非常好用的,非常方便,无需配置多少东西即可运行。

ps,关于spring的基本配置就略过了...

1.搭建spring框架(其实就是导入一些jar包)

2.在src下的resources文件夹中新建一个配置文件,命名为spring-task.xml

3.在java文件夹下编写定时任务

4.编写测试文件,运行...

接下来就是详细步骤,主要记录2跟3.

spring-task.xml

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

为什么不要在Spring的配置里,配置上XSD的版本号?因为如果没有配置版本号,取的就是当前jar里的XSD文件,减少了各种风险。而且这样约定大于配置的方式很优雅。

mytask.java

package com.spring.task;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component

public class mytask {

@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次

public void myTest(){

System.out.println("进入测试");

}

}

定时任务的java文件有两个地方需要注意

1.在类的前面添加@Component注解

2.在方法前面添加@Scheduled(cron="0/5 * * * * ? ")

TestTask类测试定时器

package com.spring.test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestTask {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext(

"classpath:spring-task.xml");

}

}

在spring中只要读取到schedule的配置文件,spring就会开始启动定时器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值