每秒检查时间

wlp8pajw  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(393)

我计划做一个twitter机器人,在我想要的时间发twitter。我已经用下面的代码获得了每秒钟的时间,但是当我确定时间是我想要的时间时,什么也没有发生,它继续打印时间,就像我设置的时间与实际时间不同,即使它们是相同的。下面是我的代码:import java.util.calendar;

  1. public class Main {
  2. public static void main(String[] args) {
  3. while (true) {
  4. Calendar a = Calendar.getInstance();
  5. //The time I want
  6. String wTime = "19:24:12";
  7. String sec = Integer.toString(a.get(Calendar.SECOND));
  8. String min = Integer.toString(a.get(Calendar.MINUTE));
  9. String hour = Integer.toString(a.get(Calendar.HOUR_OF_DAY));
  10. String time = hour + ":" + min + ":" + sec;
  11. System.out.println(time);
  12. if(time == wTime){
  13. //Tweet something
  14. }
  15. try {
  16. Thread.sleep(1000);
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }
  22. }
roejwanj

roejwanj1#

  1. ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

然后可以定义myclass:

  1. class MyClass implements Runnable {
  2. @Override
  3. public void run() {
  4. // do some needed work
  5. }
  6. }

然后你可以这样做:

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

tpgth1q72#

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

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

相关问题