Showing posts with label task. Show all posts
Showing posts with label task. Show all posts

Monday, December 5, 2016

Schedule task using Java

We can schedule a task using Java such that it will run everyday or on specified day at specified time.

Language Used:
Java

Git Repo:
https://github.com/csanuragjain/extra/tree/master/ScheduleTask

Program:

Main method:
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           System.out.println("Program started at "+new Date());  
           Calendar calendar = Calendar.getInstance();  
     calendar.add(Calendar.MINUTE,1);  
     TimerTask task = new TimerTask() {  
       @Override  
       public void run() {  
            System.out.println("Task started at "+new Date());  
            System.out.println("Hello !!!");  
       }  
      };  
      runTask(calendar,task);  
      }  

How it works:
1) We print the current data and time
2) We make a calender object which will point to current time+1 minute
3) We make a new task using TimerTask class
4) We define task content in the run method.
5) So if the task run it will print the time at which task ran along with a message Hello
6) We call the method runTask which actually schedule the task defined in step4 at time defined at step2

runTask method:
      public static void runTask(Calendar calendar, TimerTask task)  
      {  
           Timer time = new Timer();   
     time.schedule(task, calendar.getTime(), TimeUnit.SECONDS.toMillis(15));  
      }  

How it works:
1) We define an object of Timer
2) We call the schedule method. It takes 3 argument
3) First argument takes the task to be run
4) Second argument defines the time after which task will start running. We made it as current time +1
5) Third argument tells the time after which task run again after it completes. Here we made it as 15 seconds.
6) So finally when you run the program, task starts after 1 minutes and after completion it will rerun again after every 15 seconds

Output:
 Program started at Mon Dec 05 18:40:55 IST 2016  
 Task started at Mon Dec 05 18:41:55 IST 2016  
 Hello !!!  
 Task started at Mon Dec 05 18:42:10 IST 2016  
 Hello !!!  
 Task started at Mon Dec 05 18:42:25 IST 2016  
 Hello !!!  
 Task started at Mon Dec 05 18:42:40 IST 2016  
 Hello !!!  

Full Program:
 package com.cooltrickshome;  
 import java.util.Calendar;  
 import java.util.Date;  
 import java.util.Timer;  
 import java.util.TimerTask;  
 import java.util.concurrent.TimeUnit;  
 public class ScheduleTask {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           System.out.println("Program started at "+new Date());  
           Calendar calendar = Calendar.getInstance();  
     calendar.add(Calendar.MINUTE,1);  
     TimerTask task = new TimerTask() {  
       @Override  
       public void run() {  
            System.out.println("Task started at "+new Date());  
            System.out.println("Hello !!!");  
       }  
      };  
      runTask(calendar,task);  
      }  
      public static void runTask(Calendar calendar, TimerTask task)  
      {  
           Timer time = new Timer();   
     time.schedule(task, calendar.getTime(), TimeUnit.SECONDS.toMillis(15));  
      }  
 }  

Hope it helps :)

Monday, November 14, 2016

Block Windows Program using Java


We can block any window program using Java. This is done using the window taskkill command.
To run this command we make use of Runtime.getRuntime.exec

Language Used:
Java

Git Repo:
https://github.com/csanuragjain/extra/tree/master/BlockProgram

What Happens:
1) User give the name of the windows process to kill for example  for killing IE i give iexplore.exe
2) Program checks all the process every 30 seconds and see if the blocked process is running
3) If the blocked process is running then it opens the webcam and takes the picture of the person running it and saves it in the current project directory.
4) Post that it kills the blocked process by running taskkill  command

Maven Dependency:

Add below dependency for adding cam support in pom.xml
   <dependency>   
     <groupId>com.github.sarxos</groupId>   
     <artifactId>webcam-capture</artifactId>   
     <version>0.3.10</version>   
     <scope>test</scope>   
   </dependency>   

Program:

Main method:
      public static void main(String[] args) throws InterruptedException, IOException {  
           String[] monitorRunningProcess=new String[]{"tasklist.exe"};  
           String processToBlock="";  
           System.out.println("Enter the process to be blocked");  
           Scanner s=new Scanner(System.in);  
           processToBlock = s.nextLine();  
           s.close();  
           String[] killProgram=new String[]{"taskkill","/F","/IM",processToBlock};  
           System.out.println("Initiated blocking "+processToBlock);  
           while(true)  
           {  
                boolean isProgramRunning=monitorProgram(monitorRunningProcess, processToBlock);  
                if(isProgramRunning)  
                {  
                     snapshotCounter++;  
                     System.out.println("Someone ran "+processToBlock);  
                     Webcam webcam = Webcam.getDefault();  
                     webcam.setViewSize(new Dimension(640, 480));  
                     webcam.open();  
                     ImageIO.write(webcam.getImage(), "PNG", new File("User"+snapshotCounter+".png"));  
                     webcam.close();  
                     System.out.println("Picture of the Person who ran blocked program is stored at "+new File("").getAbsolutePath()+File.separator+"User"+snapshotCounter+".png");  
                     System.out.println("Killing "+processToBlock);  
                     runProgram(killProgram);  
                }  
                Thread.sleep(30000);  
           }  
      }  

How it works:

1) tasklist.exe defines all the running process in windows
2) We ask the user to give the process to be blocked
3) We prepare a string variable with the command to kill the process as taskkill /F /IM <Process to kill>
4) Now we run an infinite loop
5) We run tasklist.exe using module monitorProgram which tells if the blocked process is currently running or not
5) If we found that blocked program is running then we take the snapshot from webcam (https://cooltrickshome.blogspot.in/2016/11/take-snapshot-from-webcam-using-java-in.html)
6) Post that we kill the program simply by passing the string variable (containing taskkill) made at Step3 to runProgram module
7) After that we wait for 30 seconds and repeat from step 5

monitorProgram method:
      public static boolean monitorProgram(String[] program, String processToMonitor) throws InterruptedException, IOException  
      {  
           boolean isprocessRunning=false;  
           Process proc = Runtime.getRuntime().exec (program);  
           InputStream progOutput = proc.getInputStream ();  
           InputStreamReader inputReader=new InputStreamReader(progOutput);  
           BufferedReader reader = new BufferedReader(inputReader);            
           String line;  
           while ((line = reader.readLine()) != null)  
             {  
                     if(line.contains(processToMonitor))  
                     {  
                          isprocessRunning=true;  
                     }  
             }  
           proc.waitFor ();  
           return isprocessRunning;  
      }  

How it works:

1) We run the process passed in argument
2) We check all the output created by the program running in step 1
3) If the output contains the processToMonitor then we return true else false

runProgram method:
      public static void runProgram(String[] program) throws InterruptedException, IOException  
      {  
           Process proc = Runtime.getRuntime().exec (program);  
           InputStream progOutput = proc.getInputStream ();  
           InputStreamReader inputReader=new InputStreamReader(progOutput);  
           BufferedReader reader = new BufferedReader(inputReader);            
           String line;  
           while ((line = reader.readLine()) != null)  
             {  
                     System.out.println(line);  
             }  
           if (0 == proc.waitFor ()) {  
             System.out.println("Process completed successfully");  
           }  
           else  
           {  
                System.out.println("Their was some issue while running the program");  
           }  
      }  

How it works:
1) Already discussed at https://cooltrickshome.blogspot.in/2016/11/runmonitor-external-program-using-java.html

Sample Output:
 Enter the program to block  
 iexplore.exe  
 Initiated blocking iexplore.exe  
 Someone ran iexplore.exe  
 Picture of the Person who ran blocked program is stored at C:\Users\anurag\workspace\cooltrickshome\User1.png  
 Killing iexplore.exe  
 SUCCESS: The process "iexplore.exe" with PID 3516 has been terminated.  
 SUCCESS: The process "iexplore.exe" with PID 7432 has been terminated.  
 Process completed successfully  

Full Code:
 package com.cooltrickshome;  
 import java.awt.Dimension;  
 import java.io.BufferedReader;  
 import java.io.File;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 import java.util.Scanner;  
 import javax.imageio.ImageIO;  
 import com.github.sarxos.webcam.Webcam;  
 public class BlockWindowsProgram {  
      /**  
       * @param args  
       * @throws IOException  
       * @throws InterruptedException  
       */  
      static int snapshotCounter=0;  
      public static void main(String[] args) throws InterruptedException, IOException {  
           String[] monitorRunningProcess=new String[]{"tasklist.exe"};  
           String processToBlock="";  
           System.out.println("Enter the process to be blocked");  
           Scanner s=new Scanner(System.in);  
           processToBlock = s.nextLine();  
           s.close();  
           String[] killProgram=new String[]{"taskkill","/F","/IM",processToBlock};  
           System.out.println("Initiated blocking "+processToBlock);  
           while(true)  
           {  
                boolean isProgramRunning=monitorProgram(monitorRunningProcess, processToBlock);  
                if(isProgramRunning)  
                {  
                     snapshotCounter++;  
                     System.out.println("Someone ran "+processToBlock);  
                     Webcam webcam = Webcam.getDefault();  
                     webcam.setViewSize(new Dimension(640, 480));  
                     webcam.open();  
                     ImageIO.write(webcam.getImage(), "PNG", new File("User"+snapshotCounter+".png"));  
                     webcam.close();  
                     System.out.println("Picture of the Person who ran blocked program is stored at "+new File("").getAbsolutePath()+File.separator+"User"+snapshotCounter+".png");  
                     System.out.println("Killing "+processToBlock);  
                     runProgram(killProgram);  
                }  
                Thread.sleep(30000);  
           }  
      }  
      public static boolean monitorProgram(String[] program, String processToMonitor) throws InterruptedException, IOException  
      {  
           boolean isprocessRunning=false;  
           Process proc = Runtime.getRuntime().exec (program);  
           InputStream progOutput = proc.getInputStream ();  
           InputStreamReader inputReader=new InputStreamReader(progOutput);  
           BufferedReader reader = new BufferedReader(inputReader);            
           String line;  
           while ((line = reader.readLine()) != null)  
             {  
                     if(line.contains(processToMonitor))  
                     {  
                          isprocessRunning=true;  
                     }  
             }  
           proc.waitFor ();  
           return isprocessRunning;  
      }  
      public static void runProgram(String[] program) throws InterruptedException, IOException  
      {  
           Process proc = Runtime.getRuntime().exec (program);  
           InputStream progOutput = proc.getInputStream ();  
           InputStreamReader inputReader=new InputStreamReader(progOutput);  
           BufferedReader reader = new BufferedReader(inputReader);            
           String line;  
           while ((line = reader.readLine()) != null)  
             {  
                     System.out.println(line);  
             }  
           if (0 == proc.waitFor ()) {  
             System.out.println("Process completed successfully");  
           }  
           else  
           {  
                System.out.println("Their was some issue while running the program");  
           }  
      }  
 }  

Hope it helps :)