Advertisement
xeritt

Reverse Timer save time to text file for streaming

Jan 22nd, 2022
1,475
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.io.*;
  2. import java.util.Calendar;
  3. import java.util.Timer;
  4. import java.util.TimerTask;
  5.  
  6. public class ReverseTimer {
  7.     public static final int PERIOD = 1000;
  8.     public static String format = "%d h. %d min. %d sec.";
  9.     private int min;
  10.     private int sec;
  11.     private int h;
  12.  
  13.     public void start(String fileName, String hour, String minute){
  14.         Calendar cal = Calendar.getInstance();
  15.  
  16.         h = Integer.parseInt(hour);
  17.         min = Integer.parseInt(minute);
  18.  
  19.         cal.add(Calendar.HOUR, h);
  20.         cal.add(Calendar.MINUTE, min);
  21.  
  22.         File file = new File(fileName);
  23.         Timer timer = new Timer();
  24.  
  25.         TimerTask tsk = new TimerTask() {
  26.             @Override
  27.             public void run() {
  28.                 Calendar cur = Calendar.getInstance();
  29.                 h = cal.get(Calendar.HOUR) - cur.get(Calendar.HOUR);
  30.                 min = cal.get(Calendar.MINUTE) - cur.get(Calendar.MINUTE) - 1;
  31.                 sec = 59 - Math.abs(cur.get(Calendar.SECOND) - cal.get(Calendar.SECOND));
  32.                 String str = String.format(format, h, min , sec);
  33.                 writeData(file, str);
  34.                 System.out.println(str);
  35.                 if (h<=0 && min<=0 && sec<=0){
  36.                     timer.cancel();
  37.                 }
  38.             }
  39.         };
  40.         timer.schedule(tsk, 0, PERIOD);
  41.     }
  42.  
  43.  
  44.     public static void main(String[] args) {
  45.         ReverseTimer tm = new ReverseTimer();
  46.         tm.start(args[0], args[1], args[2]);
  47.     }
  48.  
  49.     private static void writeData(File file, String data) {
  50.         try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))){
  51.             writer.write(data);
  52.         } catch (FileNotFoundException e) {
  53.             e.printStackTrace();
  54.         } catch (IOException e) {
  55.             e.printStackTrace();
  56.         }
  57.     }
  58. }
  59.  
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement