JAVA 优秀架包:http://www.admin10000.com/document/8155.html
/*
启动一个java app或者服务
*/
import org.eclipse.jetty.server.Server;
public class QuartzTest {
/** *//**
* @param args
*/
public static void main(String[] args) throws Exception {
Server server = new Server(8899);
server.setHandler(new ScheduleRouteHandle());
System.out.println("启动服务");
server.start();
server.join();
}
}
/*
启动一个定时任务,或者监听请求
*/
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
* Created by 8899man on 16/6/16.
*/
public class ScheduleRouteHandle extends AbstractHandler {
//public class ScheduleRouteHandle extends AbstractHandler {
//private final Logger logger = Logger.getLogger(ScheduleRouteHandle.class);
static{
System.out.println("static调用");
// TODO Auto-generated method stub
SimpleDateFormat DateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date d = new Date();
String returnstr = DateFormat.format(d);
CreateVmJob job = new CreateVmJob();
String job_name ="create_vm";
try {
System.out.println(returnstr+ "【系统启动】");
QuartzManager.addJob(job_name,job,"0/5 * * * * ?"); //每2秒钟执行一次
} catch (Exception e) {
e.printStackTrace();
}
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
//log(target, request);
System.out.println("调用");
// TODO Auto-generated method stub
SimpleDateFormat DateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date d = new Date();
String returnstr = DateFormat.format(d);
TestJob job = new TestJob();
String job_name ="11";
try {
System.out.println(returnstr+ "【系统启动】");
QuartzManager.addJob(job_name,job,"0/5 * * * * ?"); //每2秒钟执行一次
// Thread.sleep(10000);
// System.out.println("【修改时间】");
// QuartzManager.modifyJobTime(job_name,"0/10 * * * * ?");
// Thread.sleep(20000);
// System.out.println("【移除定时】");
// QuartzManager.removeJob(job_name);
// Thread.sleep(10000);
//
// System.out.println("/n【添加定时任务】");
// QuartzManager.addJob(job_name,job,"0/5 * * * * ?");
} catch (Exception e) {
e.printStackTrace();
}
}
private void log(String target, HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
sb.append("get a request[" + target + "] ");
for (String key : request.getParameterMap().keySet()) {
String value = request.getParameter(key);
if (value != null && value.length() > 300) {
value = value.substring(0, 300) + "...";
}
sb.append(key).append("=").append(value).append(",");
}
sb.append("ip=" + request.getHeader("X-Forwarded-For"));
//logger.info(sb.toString());
}
}
/*作业类:
*/
import com.databasepool.MySqlConn;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by 8899man on 16/6/20.
*/
public class CreateVmJob implements Job {
SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = new Date();
String returnstr = DateFormat.format(d);
ThreadPoolExecutor executor = new ThreadPoolExecutor(20,Integer.MAX_VALUE , 2000, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue(30));
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println(returnstr+"★★★★★★★★★★★cccccvm");
String sql = "select * from process_vm_interface where state='1'";
MySqlConn mySqlConn = new MySqlConn();
ResultSet rs = null;
try {
ArrayList vbList = mySqlConn.readVmBySql(sql);
for (int i=0;i
String orderid = vbList.get(i).getOrderid();
System.out.println("打印orderid:"+orderid);
MyTask myTask = new MyTask(i,orderid);
executor.execute(myTask);
//System.out.println("线程池中线程数目:"+executor.getPoolSize()+",队列中等待执行的任务数目:"+
// executor.getQueue().size()+",已执行玩别的任务数目:"+executor.getCompletedTaskCount());
}
executor.shutdown();
/*int col = rs.getMetaData().getColumnCount();
while (rs.next()) {
rs.getString("order_id");
for (int i = 1; i <= col; i++) {
System.out.print(rs.getString(i) + "\t");
if ((i == 2) && (rs.getString(i).length() < 8)) {
System.out.print("\t");
}
}
System.out.println("");
}*/
} catch (Exception e) {
e.printStackTrace();
}
if (rs!=null){
}
}
}
/*
*/
package com.xx.httptest;
/**
* Created by 8899man on 16/6/27.
*/
import java.io.*;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
public class HttpClientUtil {
static final int VIEW_TIMEOUT = 12000;
static final boolean VIEW_OUTPUT = true;
static final String VIEW_METHOD = "POST";
static final String VIEW_CHAR_CODE = "UTF-8";
static String BASEURL="http://localhost:8030/";
static{
Properties props = new Properties();
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(
HttpClientUtil.class.getResource("/dbconn.properties").getFile()));
props.load(in);
if(props.get("BASEURL")==null){
System.out.println("BASEURL:is null");
}
BASEURL= String.valueOf(props.get("BASEURL"));
in.close();
} catch (Exception e) {
e.printStackTrace();
if(in!=null)
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void test() {
try{
String result1 = "";
HttpClient httpclient=new HttpClient();
HttpClientParams hc = new HttpClientParams();
hc.setParameter("t1","yangqing1");
hc.setParameter("t2","yangqing2");
httpclient.setParams(hc);
System.out.println("打印传递的参数---------->");
//System.out.println(htt().toString());
String urlpath=BASEURL+"workflowapi/workflowextend";
System.out.println(urlpath);
GetMethod getmethod=new GetMethod(urlpath);
int sendStatus=0;
try {
sendStatus=httpclient.executeMethod(getmethod);
result1 = getmethod.getResponseBodyAsString();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//释放
System.out.println(sendStatus);
getmethod.releaseConnection();
}
System.out.println(result1);
JSONObject obj = JSON.parseObject(result1);
String object = obj.getString("code");
System.out.println("打印解析------->");
System.out.println(object);
return;
}catch(Exception ce){
ce.printStackTrace();
return;
//return "{\"msg\": \"请求失败!\",\"status\": 500}";
}
/*try {
URL url = new URL(urlpath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(VIEW_TIMEOUT);
connection.setDoOutput(VIEW_OUTPUT);
connection.setRequestMethod(VIEW_METHOD);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
String fileMsg = "data=" + URLEncoder.encode(data, VIEW_CHAR_CODE) + "&username=" + username + "&sdns-api=" + password;
InputStream fileInputStream = new ByteArrayInputStream(fileMsg.getBytes(VIEW_CHAR_CODE));
byte[] bytes = new byte[1024];
int numReadByte = 0;
while ((numReadByte = fileInputStream.read(bytes, 0, 1024)) > 0) {
out.write(bytes, 0, numReadByte);
}
out.flush();
fileInputStream.close();
int code = connection.getResponseCode();
DnsCallHistoryBean dnsCallHistory = new DnsCallHistoryBean();
if (code != 200) {
dnsCallHistory.setMsg("访问错误,错误码" + code);
return new TwoTuples(code, dnsCallHistory);
}
}catch (Exception e){
System.out.println(e);
}*/
}
private static HttpMethod postMethod(String url) throws IOException{
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");
NameValuePair[] param = { new NameValuePair("startCity","杭州"),
new NameValuePair("lastCity","沈阳"),
new NameValuePair("userID",""),
new NameValuePair("theDate","") } ;
post.setRequestBody(param);
post.releaseConnection();
return post;
}
public static void main(String[] args){
HttpClientUtil main = new HttpClientUtil();
main.test();
//HttpClient httpClient = new HttpClient();
//HttpMethod httpMethod = new HeadMethod();
}
}
/*
数据库连接 ,可以读取配置文件
*/
import com.xx.VmBean;
import java.sql.*;
import java.util.ArrayList;
/**
* Created by 8899man on 16/6/20.
*/
public class MySqlConn {
private static Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/cmdb";
String username = "root";
String password = "yangqing";
Connection conn = null;
try {
Class.forName(driver); //classLoader,加载对应驱动
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public ArrayList readVmBySql(String sql) throws Exception{
if (sql == null || "".equals(sql)) {
return null;
}
Statement statement = null;
MysqlPool mysqlPool = new MysqlPool();
ArrayList arrylist = new ArrayList();
java.sql.Connection connection = mysqlPool.getConnection();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
String orderid = rs.getString("order_id");
String state = rs.getString("state");
String create_id = rs.getString("create_id");
VmBean vb = new VmBean();
vb.setCrateid(create_id);
vb.setState(state);
vb.setOrderid(orderid);
arrylist.add(vb);
}
} catch (Exception e) {
throw e;
} finally {
if (statement != null) {
statement.close();
}
mysqlPool.close(connection);
}
return arrylist;
}
public int updateBySql(String sql) throws Exception{
if (sql == null || "".equals(sql))
return 0;
Statement statement = null;
MysqlPool mysqlPool = new MysqlPool();
java.sql.Connection connection = mysqlPool.getConnection();
int rs = 0;
try {
statement = connection.createStatement();
rs = statement.executeUpdate(sql);
} catch (Exception e) {
throw e;
} finally {
if (statement != null) {
statement.close();
}
mysqlPool.close(connection);
}
return rs;
}
private static void getAll() {
//Connection conn = getConn();
MysqlPool mysqlPool = new MysqlPool();
Connection conn = mysqlPool.getConnection();
String sql = "select * from process_base_info";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement)conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getString("process_name") + " ");
}
} catch (SQLException e) {
e.printStackTrace();
}
//return null;
}
public static void main(String[] args){
getAll();
getAll();
getAll();
getAll();
//MySqlConn.getAll();
/*String sql = "select * from process_base_info";
try {
MySqlConn mySqlConn = new MySqlConn();
mySqlConn.readBySql(sql);
} catch (Exception e) {
e.printStackTrace();
}*/
/*String sql ="update process_base_info set introduce='8888' where process_id=3";
MySqlConn mySqlConn = new MySqlConn();
try {
int k = mySqlConn.updateBySql(sql);
System.out.println("更新记录:"+k);
} catch (Exception e) {
e.printStackTrace();
}*/
}
}
/*
连接池,可以参考commons pool 对象池开源实现
*/
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;
import java.sql.Connection;
public class MysqlPool {
protected final Logger logger = Logger.getLogger(MysqlPool.class);
private static BasicDataSource ds = null;
//private ConnPoolParamEnum connPoolParamEnum;
private String validationQuery = "select 1";
private String usename = "root";
private String password = "yangqing";
private String url = "jdbc:mysql://localhost:3306/cmdb";
private String driver = "com.mysql.jdbc.Driver";
public MysqlPool(){
}
public MysqlPool(String url, String username, String password, String driverClass) {
this.url = url;
this.usename = username;
this.password = password;
this.driver = driverClass;
//connPoolParamEnum = ConnPoolParamEnum.get(dbtype, project);
init();
}
private void init() {
ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUsername(usename);
ds.setPassword(password);
ds.setUrl(url);
ds.setInitialSize(20);
ds.setMaxActive(100);
ds.setMaxIdle(80);
ds.setMinIdle(20);
ds.setMaxWait(5000);
ds.setTestOnBorrow(true);
ds.setValidationQuery(validationQuery);
logger.info("init connection pool[" + url + "]");
System.out.println("init connection pool");
}
public synchronized Connection getConnection() {
if (ds == null)
init();
Connection connection = null;
try {
connection = ds.getConnection();
logger.info("get a connection from pool [" + url + "],idle connection[" + ds.getNumIdle() + "]");
} catch (Exception e) {
logger.error(e);
}
return connection;
}
public void close(Connection connection) {
if (connection != null) {
try {
connection.close();
logger.info("release a connection to pool [" + url + "],idle connection[" + ds.getNumIdle() + "]");
} catch (Exception e) {
logger.error(e);
}
}
}
}
/*
MyTask任务 _多线程传参方式,可以参考另外一篇文章,多线程传参数
*/
/**
* Created by yq on 16/6/16.
*/
public class MyTask implements Runnable{
private int taskNum;
private String orderid;
/*构造函数传参数*/
public MyTask(int num,String orderid) {
this.taskNum = num;
this.orderid = orderid;
}
//@Override
public void run() {
System.out.println("正在执行task "+taskNum);
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task "+taskNum+"执行完毕,单号——>"+orderid);
}
}
POM.XML文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
lsquartz
lingshuquartz
1.0-SNAPSHOT
com.lingshu.quartz
http://maven.apache.org
UTF-8
3.0.5.RELEASE
org.eclipse.jetty
jetty-server
9.2.14.v20151106
org.json
json
20090211
junit
junit
3.8.1
test
org.apache.httpcomponents
httpclient
4.3.6
mysql
mysql-connector-java
5.1.38
commons-fileupload
commons-fileupload
1.3.1
org.apache.httpcomponents
httpmime
4.5.1
org.quartz-scheduler
quartz
1.8.5
org.apache.commons
commons-pool2
2.2
commons-lang
commons-lang
2.5
commons-dbcp
commons-dbcp
1.4
log4j
log4j
1.2.17
commons-httpclient
commons-httpclient
3.1
net.sf.json-lib
json-lib
2.4
com.alibaba
fastjson
1.2.3
${project.artifactId}
org.apache.maven.plugins
maven-dependency-plugin
2.4
copy-dependencies
package
copy-dependencies
${project.build.directory}/lib
false
false
true
org.apache.maven.plugins
maven-jar-plugin
2.4
true
lib/
com.xx.QuartzTest