Search code examples
javamultithreadingtwittertwitter4j

Kill thread in java after a certain time


I have a use case as following (in JAVA)

I receive a request from client

E.g: Do twitter streaming task till this date.

  • Task = twitter streaming
  • Keywords = {"#Today", "#apple"}
  • Time = till 5 feburary 2017

What I do is, I open a new thread on every request that I receive and start my task which is streaming of tweets and saving them to the database.

What I want to do is the thread should stop streaming and should get killed after this date (Feb 5).

How can I implement this type of use-case?


Solution

  • You can use the Calendar class and check that e.g.

    Calendar c = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("CET")));
    c.set(Calendar.MONTH, 1)
    c.set(Calendar.DAY_OF_MONTH, 5)
    c.set(Calendar.HOUR_OF_DAY, 23);
    c.set(Calendar.MINUTE, 59);
    c.set(Calendar.SECOND, 59);
    c.set(Calendar.MILLISECOND, 999);
    
    while(true){
     Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("CET")));
     if(cal.getTime().after(c.getTime()) return;
    }