spring框架
1,定时任务
@Component public class HelloTask { @Scheduled(cron = "0/5 * * * * *") public void sayHello(){ String helloStr="hello "; System.out.println(helloStr); } }
2,配置spring配置文件applicationContext.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: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/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置扫描注解的路径-->
<context:component-scan base-package="com.company.task"/>
<!-- 方式一:-->
<task:annotation-driven scheduler="scheduler" mode="proxy"/>
<task:scheduler id="scheduler" pool-size="10"/>
<!--方式二:-->
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
</beans>
3,在main方法中加载配置文件
public class App {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("Hello World!");
}
}
springboot框架
1,定时任务
@Component public class HelloTask { @Scheduled(cron = "0/5 * * * * *") public void sayHello(){ String helloStr="hello "; System.out.println(helloStr); } }
2,启动程序上添加注解@EnableScheduling
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootScheduleApplication.class, args);
}
}
注意:定时任务的方法只能为无参数的方法。
posted on
浙公网安备 33010602011771号