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

    主方法:

    1. public static void main(String[] args){
    2. TestTimer tt = new TestTimer();
    3. try {
    4. tt.test();
    5. } catch (ParseException e) {
    6. e.printStackTrace();
    7. }
    8. }