Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2. // Desc: Checks to see if this process is already running and if so, prevents this from running
  3. // Args: none
  4. // Ret : none - exits the applicaiton if an instance is already running
  5. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6. public static void checkIfAlreadyRunning()
  7. {
  8.     boolean running = false;
  9.     String directoryLocation = "running_scripts/";
  10.     String filename = directoryLocation + "my_application.txt";
  11.  
  12.     File scriptDir = new File(directoryLocation);
  13.  
  14.     // Create the directory structure if it doesn't exist.
  15.     if (!scriptDir.exists())
  16.     {
  17.         scriptDir.mkdirs();
  18.     }
  19.  
  20.     // Create the file if it doesnt exist.
  21.     File scriptFile = new File(filename);
  22.     if (!scriptFile.exists())
  23.     {
  24.         try
  25.         {
  26.             scriptFile.createNewFile();
  27.         }
  28.         catch (Exception e)
  29.         {
  30.             System.out.println("Error creating script file that didnt exist: " + e);
  31.             System.exit(1);
  32.         }
  33.        
  34.     }
  35.  
  36.     // If can get a lock on the file then this process is not already running.
  37.     try
  38.     {
  39.         FileChannel channel = new RandomAccessFile(scriptFile, "rw").getChannel();          
  40.         FileLock lock = channel.tryLock();
  41.        
  42.         // Trylock returns null if overlapping lock, not an error
  43.         if (lock == null)
  44.         {
  45.             String message = "You are only allowed to have one running instance of " +
  46.                              "this app.";
  47.             System.out.println(message);
  48.             System.exit(0);
  49.         }
  50.        
  51.     }
  52.     catch (Exception p)
  53.     {
  54.         System.out.println("checkIfAlreadyRunning Error " + p);
  55.         System.exit(1);
  56.     }
  57.    
  58. }