1

I'm planning to make a Twitter bot that tweets at the hour I want. I've managed to get the time every second with the following code, but when I the time is the time I want, nothing happens, it continues printing the time, like the time I've set is different to the actual time even if they're the same. Here's my code: import 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();
            }
        }
    }
}
ivykoko
  • 71
  • 2
  • 9

2 Answers2

1

Use .equals() instead of == for comparing strings:

if (time.equals(wTime)) {
    // Tweet something
}
Austin
  • 5,625
  • 1
  • 29
  • 43
1
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

Then you can define MyClass class:

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

And then you can do this:

scheduler.scheduleAtFixedRate(new MyClass(), 1, 1, TimeUnit.SECONDS);
DmitryKanunnikoff
  • 2,226
  • 2
  • 22
  • 35