Simulasi Quartz

Lama tak menulis, terkait menjadi korban peminjaman resource ke project lain, jadinya penasaran coba teknologi quartz yang kebetulan dipakai di client tersebut.

Dari yang saya pake, intinya quartz kaya service yang siap jalan dalam waktu tertentu, dimana waktu mulai dll kita atur sendiri. penjelasan detail nya mungkin bisa dilihat di website nya sendiri, hehe.

Teknologi yang dipake:

Source code:
quartz.properties

org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

MainView.java

package samplequartz;
 
import java.util.logging.Level;
import java.util.logging.Logger;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
 
public class MainView extends javax.swing.JFrame {
 
    private int threadCount = 0;
 
    /**
     * Creates new form MainView
     */
    public MainView() {
        initComponents();
        setLocationRelativeTo(null);
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
 
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
 
        jButton1.setText("Add Job");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        jButton2.setText("Add Thread");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );
 
        pack();
    }// </editor-fold>                        
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // define the job and tie it to our HelloJob class 
            JobDetail job = JobBuilder.newJob(SampleJob.class).withIdentity("job" + String.valueOf(threadCount)).usingJobData("count", String.valueOf(threadCount)).build();
            Variables.status.put("Process_" + threadCount, "");
            // Sample Job Commang Line
//            JobDetail job = JobBuilder.newJob(SampleJobFrame.class).withIdentity("job" + String.valueOf(threadCount)).usingJobData("count", String.valueOf(threadCount)).build();
 
            // Sample Job with frame
//            JobDetail job = JobBuilder.newJob(SampleJobDialog.class).withIdentity("job" + String.valueOf(threadCount)).usingJobData("count", String.valueOf(threadCount)).build();
 
            threadCount++;
 
            // specify the running period of the job
            Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();
 
            //schedule the job
            SchedulerFactory schFactory = new StdSchedulerFactory();
            Scheduler sch = schFactory.getScheduler();
            sch.start();
            sch.scheduleJob(job, trigger);
 
        } catch (SchedulerException ex) {
            Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        
 
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        SampleThread st = new SampleThread();
        st.start();
//        Variables.threadCount++;
    }                                        
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
 
            public void run() {
                new MainView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration                   
}

SampleJob.java

package samplequartz;
 
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
public class SampleJob implements Job {
 
    public SampleJob() {
    }
 
    public void writeData(String count) {
        BufferedWriter bw = null;
        try {
            String filePath = "D:\\";
            String fileName = filePath + "file_" + count + ".txt";
 
            bw = new BufferedWriter(new FileWriter(fileName));
 
            for (int i = 0; i < 1000; i++) {
                bw.write(Util.getInstance().generateStringRow());
                bw.newLine();
            }
        } catch (IOException ex) {
            Logger.getLogger(SampleJob.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                bw.close();
            } catch (IOException ex) {
                Logger.getLogger(SampleJob.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
 
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        JobDataMap data = context.getMergedJobDataMap();        
        String threadCount = data.getString("count");
 
        if (! Variables.status.get("Process_" + threadCount).equals("Progress")) {
            Variables.status.put("Process_" + threadCount, "Progress");
            System.out.println("Job " + data.getString("count") + " Process at " + new Date());
 
            writeData(data.getString("count"));
 
            System.out.println("Job " + data.getString("count") + " Done at " + new Date());
            Variables.status.put("Process_" + threadCount, "Success");
        }
    }
 
//    public static void main(String args[]) {
//        SampleJob s = new SampleJob();
//        s.writeData("0");
//    }
}

Variables.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package samplequartz;
 
import java.util.HashMap;
import java.util.Map;
 
public class Variables {
//    public static int threadCount = 0;
    public static Map<String, String> status = new HashMap<>();
}

Util.java

package samplequartz;
 
public class Util {
    private static Util util;
 
    public static Util getInstance() {
        if (util == null) {
            util = new Util();
        }
        return util;
    }
 
    public String generateStringRow() {
        StringBuilder result = new StringBuilder();
        for (int i = 0;i < 10000; i++) {
            for(int j=0; j < 10; j++) {
                result.append(j);
            }
            result.append("|");
        }
        return result.toString();
    }
 
}

Hasil
Simulation

Diskusi:

  • quarts.properties untuk atribut org.quartz.threadPool.threadCount berfungsi mendefinisikan total thread yang akan digunakan dalam quartz
  • Quartz menggunakan teknologi thread untuk eksekusi proses

CMIIW.

Marifnst, 2015-12-21

Leave a Reply

Your email address will not be published. Required fields are marked *

Afiseaza emoticoanele Locco.Ro