原生方式
package javatimer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class JavaTimer {
//做一个小计时器
//模拟每天晚上 给所有同学发送短信(邮件)
public static void main(String[] args) throws ParseException {
System.out.println("开始运行");
//存储用户名、手机号、邮箱......
//最好创建一个集合(随时扩容)
String[] userArray={"小慧","小榆","小小慧","久久"};
ArrayList<String> userList=new ArrayList<>(Arrays.asList(userArray));
//自定义发送时间和发送间隔
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
Date firstTime=sdf.parse("2021-08-23 18:28:30");
//找一个计时器对象帮我们计时,时间到了就做事
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {//最终的任务
for(String user: userList){
System.out.println(user+"你睡了吗");
}
}
},firstTime,3000);
}
}
Spring方式管理Timer
需要的包
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation=" http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<!--我们自己定义的任务类交给Spring来管理-->
<bean id="springTask" class="springtimer.SpringTask"></bean>
<!--创建一个Spring提供好的计时器对象,用来做倒计时管控(可以理解为前面的Timer对象)-->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="springTask"></property>
<property name="targetMethod" value="doSomething"></property>
</bean>
<!--创建一个Spring提供的触发器对象,一旦上面的目标对象及方法确定,触发器就开始进行实践的计算及循环-->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail"></property>
<property name="cronExpression" value="35/5 52 19 * * ?"></property>
</bean>
<!-- 将我们设置好的触发器对象 放置在一个Spring管理的集合对象中 SchedulerFactoryBean -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
</beans>
SpringTask
package springtimer;
import java.util.ArrayList;
import java.util.Arrays;
/**
* 可以理解为是刚才的那个Task
* 类中只有一个具体的事情(任务)
* 没有timer帮我们做倒计时
*/
public class SpringTask {
String[] userArray={"小慧","小榆","小小慧","久久"};
ArrayList<String> userList=new ArrayList<>(Arrays.asList(userArray));
//具体的事情(刚才那个任务的方法)
public void doSomething() {
for(String user: userList){
System.out.println(user+"你睡了吗");
}
}
}
TestMain
package springtimer;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("ApplicationContext.xml");
}
}