public class TestTimer {//用来存储所有人的电话号private ArrayList<String> userBox = new ArrayList<>();{userBox.add("a");userBox.add("b");userBox.add("c");}//设计一个方法 每隔一段时间 发送垃圾短信public void test() throws ParseException {System.out.println("即将开始!");//计时器Timer timer = new Timer();//将给定的日期格式转换为Date形式的时间SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date firstTime = sdf.parse("2021-3-24 9:42:45:");timer.schedule(new TimerTask() {//TimerTask是抽象类 本不可以new对象 但是匿名内部类相当于把子类的方法拿过来重写了public void run() {for(int i = 0;i<userBox.size();i++){System.out.println("给"+userBox.get(i)+"发送了一条消息:你好帅");}System.out.println("做了坏事 哈哈哈");}},firstTime,3000);//firstTime是开始的时间 每隔3秒发送一次}}
主方法:
public static void main(String[] args){TestTimer tt = new TestTimer();try {tt.test();} catch (ParseException e) {e.printStackTrace();}}
