TelegramBotsExample
TelegramBotsExample copied to clipboard
How to update bot in production mode?
Hey, I thought about updating my bot while he is still in production mode and could possibly do something at the moment.
I came out with this solution:
Creating a new class that is responsible for interactions with the server console
public class BotMaster extends Thread {
private BotSession session;
public void run(){
Scanner scanner = new Scanner(System.in);
String c;
while((c = scanner.nextLine()) != null){
if(c.equals("stop")){
System.out.println("[INFO] Start shutting down this instance");
this.session.close();
System.out.println("[OK] Closed session. Up to now, we cannot receive any updates. Shutting down program when there are no more pending actions");
while(EchoHandler.isInUse()){
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//end catch()
}//end while()
System.out.println("[OK] Shutting down full instance");
scanner.close();
currentThread().interrupt();
break;
}//end if()
}//end while()
}//end run()
public void setSession(BotSession session){
this.session = session;
}//end setSession()
}//end class
Added also one method to my updatehandler
private static int pendingActions;
public static boolean isInUse(){
return !(EchoHandler.pendingActions == 0);
}//end isInUse()
Every time onUpdateReceived() is called, pendingActions is counted up, and before end of the method call it's also counted down
My Main.java
public static void main(String[] args) throws IOException, InterruptedException {
BotSession session= null;
BotMaster master = new BotMaster();
master.start();
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
session = telegramBotsApi.registerBot(new EchoHandler());
master.setSession(session);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
System.out.println(e.getApiResponse());
}//end catch()
while(master.isAlive()){
}//end while()
System.exit(-1);
}//end main()
How I use it
- type
stopinto the server console <- now this instance cannot receive any updates. But it can send something - next instance is started <- this instance is now responsible for new updates.
- the old instance will shut down when all pending actions are processed
Has anybody a better way to update bots in production mode?