Results 1 to 8 of 8
  1. #1
    AndyGB is offline Member
    Join Date
    Sep 2016
    Posts
    4
    Rep Power
    0

    Default My background service application

    Hello all,

    I have been learning Java for a few days now and I've created the basic outline of my application, as shown below. The application is rather simple. It is designed to be a background service which runs every xx number of seconds to extract data from a webpage, but only if it's enabled to do so. The application loops round with a delay based on the waitTime(), which retrieves a value from MySQL. But the application only run processHTML() if the isEnabled() returns true, which is based on a setting within MySQL. I think I've got the concept for this okay, although who am I to say :P

    What confuses me is when I come to connect to a MySQL database. I think it's fair to say every tutorial I have looked at connects to MySQL differently. Some tutorials connect directly in the main(), others have a dedicated function/method, while others do it in a separate package. So, as you'll see all of my functions require MySQL at some point. So I guess I just need help on where to connect, and where to disconnect. Also any further advice on my code would be great :D


    Java Code:
    public class MyApplication {
    		
    	public static void main(String[] args) throws Exception {		
    		// Create looping
    		while (1 == 1) {			
    			if (isEnabled()) {
    				// The service is allowed, get and process the html				
    				processHTML();				
    			}			
    			// Wait x number of milliseconds before running loop again
    			Thread.sleep(waitTime());			
    		}		
    	}
    	
    	public boolean isEnabled() {
    		// Looks in database to see if the service is allowed to run
    	}
    	
    	public int waitTime() {
    		// Looks in database for the waitTime setting
    	}
    	
    	public void processHTML() {
    		// Get HTML and extract data
    		
    		// Save extracted data in database
    	}
    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: My background service application

    Treat the database as a service, so stick it in its own class:

    Java Code:
    public class MyDatabase {
        // Connection parameters here
    
        public boolean isEnabled() {
            // Looks in database to see if the service is allowed to run
        }
         
        public int waitTime() {
            // Looks in database for the waitTime setting
        }
         
        public void saveHTML(String html) {
            // Save extracted data in database
        }
    
    }
    That gives you a simple small class that does a fairly clear cut job (it talks to the database to either read or save data) that you can then test in isolation happily.
    When that works you can simply plug it into your other class.

    One rule I (and many others) use is "get out of main as quick as you can".

    Java Code:
    public class Main {
        public static void main(String[] args) {
            new ProcessHtml().process();
        }
    }
    
    ...
    
    public class ProcessHtml {
    
        private MyDatabase myDatabase = new MyDatabase();
    
        public void process() {
            while (1 == 1) {            
                if (myDatabase.isEnabled()) {
                    // The service is allowed, get and process the html             
                    processHTML();              
                }           
                // Wait x number of milliseconds before running loop again
                Thread.sleep(myDatabase.waitTime());           
            }       
        }
    
        ... other methods here
    }
    Something along those lines.
    It means you get away from thinking about the main method and get into thinking in terms of how your classes interact with each other.

    Note the above is fairly rough and ready...
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    AndyGB is offline Member
    Join Date
    Sep 2016
    Posts
    4
    Rep Power
    0

    Default Re: My background service application

    Okay thanks, I'll go amend the code...

    But do I Connect and Disconnect to MySQL within each function, every time it's called?

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: My background service application

    Depends on the database, its location, what your timeouts are etc.

    This doesn't look multi threaded, so that won't apply.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    AndyGB is offline Member
    Join Date
    Sep 2016
    Posts
    4
    Rep Power
    0

    Default Re: My background service application

    I'm used to coding in PHP, so I would have connected to MySQL, run all various code, then disconnect.
    How do I do it that way in Java? Would this go at the top and bottom of the while loop?

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: My background service application

    I would do the connection the first time you need it, inside (using my example above) the MyDatabase class.

    I don't know what your full use case is, so anything I say is not necessarily correct.
    For example, if this is going to run for ages then you might need to think about sticking checks in to ensure the database hasn't closed the connection on you.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    AndyGB is offline Member
    Join Date
    Sep 2016
    Posts
    4
    Rep Power
    0

    Default Re: My background service application

    Okay, so this is where I got up to, does it look okay so far?


    Java Code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class MySQL {
    	
    	public static Connection getConnection() throws Exception {
    		  try {
    			  String driver = "com.mysql.jdbc.Driver";
    			  String url = "jdbc:mysql://localhost/pof?useSSL=false";
    			  String username = "java";
    			  String password = "java";
    			  Class.forName(driver);		  
    			  Connection conn = DriverManager.getConnection(url,username,password);
    			  System.out.println("Connection made");	
    			  return conn;
    		  } catch (Exception e) {
    			  System.out.println(e);
    		  }  
    		return null;	  
    	  }
    	
    	public static boolean isEnabled() throws SQLException, Exception {
    		int isEnabled = 0;
    		String query = "SELECT 1 FROM configuration WHERE name = 'ExtractEnabled' AND value = '1' LIMIT 1";
    		Statement stmt = getConnection().createStatement();
    		ResultSet rset = stmt.executeQuery(query);		
    		while (rset.next()){
    			isEnabled = rset.getInt(1);
    		}				
    		switch (isEnabled) {
    	        case 1:
    	            return true;
    	        default:
    	            return false;
    	    }
    	}
    	
    	public static int waitTime() throws SQLException, Exception {
    		int waitTime = 20000;
    		String query = "SELECT value FROM configuration WHERE name = 'ServiceWaitTime' LIMIT 1";
    		Statement stmt = getConnection().createStatement();
    		ResultSet rset = stmt.executeQuery(query);		
    		while (rset.next()){
    			waitTime = rset.getInt(1);
    		}		
    		return waitTime;
    	}
    	
    	public static int nextCustomer() throws SQLException, Exception {
    		int customerId = 0;
    		String query = "SELECT customerid FROM customers WHERE status IN (0, 1) LIMIT 1";
    		Statement stmt = getConnection().createStatement();
    		ResultSet rset = stmt.executeQuery(query);		
    		while (rset.next()){
    			customerId = rset.getInt(1);
    		}
    		return customerId;
    	}
    	
    	public static int lookupKey(String type, String name) throws SQLException, Exception {
    		int lookupKey = 0;
    		String query = "SELECT lookupkey FROM lookupkeys WHERE lookuptype = ? AND lookupname = ? LIMIT 1";
    		PreparedStatement pstmt = getConnection().prepareStatement(query);
    		pstmt.setString (1, type);
    		pstmt.setString (2, name);	
    		pstmt.executeQuery();
    		ResultSet rset = pstmt.executeQuery();
    		
    		while (rset.next()){
    			lookupKey = rset.getInt(1);
    		}
    		return lookupKey;
    	}
    
    }
    Last edited by AndyGB; 09-21-2016 at 09:25 PM.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: My background service application

    First, try and avoid static stuff like that.
    You should be thinking in terms of objects that do things, not just chunks of code.

    If your loop code were to look like this:
    Java Code:
    while (true) {
        MySQL mySQL = new MySQL();
        // do everything else
        // sleep
    }
    That would mean you could open the connection in the constructor and keep it open to the end.
    It does mean you need to provide a way of closing the connection in that class.

    Note, if you fail to get a connection you should log it and skip that loop (treat it as not enabled).
    There's no point returning a null. Use the exception handling.

    Java Code:
    MySQL mySQL;
    try {
        mySQL = new MySQL();  // assumes we open the connection here
        ... do things
    } catch (SQLException ex) {
        mySQL.close();
    }
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Creating a background service in java
    By prashant in forum New To Java
    Replies: 1
    Last Post: 12-12-2013, 08:28 AM
  2. Background application
    By nando88 in forum Advanced Java
    Replies: 5
    Last Post: 09-04-2013, 05:10 PM
  3. How to run a service in the background?
    By aianta in forum New To Java
    Replies: 4
    Last Post: 08-21-2013, 02:00 PM
  4. Doing background task in Swing application
    By Heatryn in forum Advanced Java
    Replies: 2
    Last Post: 07-05-2012, 01:27 AM
  5. Java application as window service
    By sijitg in forum Advanced Java
    Replies: 2
    Last Post: 09-06-2010, 10:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •