【问题标题】:Check time every second每秒检查一次时间
【发布时间】:2014-04-15 12:35:04
【问题描述】:

我打算制作一个 Twitter 机器人,可以在我想要的时间发推文。我已经设法使用以下代码每秒获取时间,但是当我的时间是我想要的时间时,什么也没有发生,它会继续打印时间,就像我设置的时间与实际时间不同,即使他们是一样的。这是我的代码: 导入 java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        while (true) {
            Calendar a = Calendar.getInstance();

            //The time I want
            String wTime = "19:24:12";

            String sec = Integer.toString(a.get(Calendar.SECOND));
            String min = Integer.toString(a.get(Calendar.MINUTE));
            String hour = Integer.toString(a.get(Calendar.HOUR_OF_DAY));
            String time = hour + ":" + min + ":" + sec;

            System.out.println(time);
            if(time == wTime){
                //Tweet something
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

【问题讨论】:

  • 字符串用 .equals 而不是 == 检查
  • 使用来自java.util.TimerTimer 类或来自java.util.TimerTaskTimerTask
  • 谢谢这是问题
  • 另外,请注意 sleep(1000) 是个坏主意。您的代码需要几毫秒才能运行,您可能会在 19:24:11:990 开始睡眠,并从 Calendar.getInstance 以 19:24:13:003 的时间返回。更好的睡眠(1000-System.currentTimeMillis()%1000)。
  • 使用 while(true) 是个好主意吗? @GuntramBlohm

标签: java multithreading twitter


【解决方案1】:

使用.equals() 而不是== 比较字符串:

if (time.equals(wTime)) {
    // Tweet something
}

【讨论】:

    【解决方案2】:
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
    

    然后就可以定义 MyClass 类了:

    class MyClass implements Runnable {
        @Override
        public void run() {
            // do some needed work
        }
    }
    

    然后你可以这样做:

    scheduler.scheduleAtFixedRate(new MyClass(), 1, 1, TimeUnit.SECONDS);
    

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多