有時(shí)候某個(gè)單體Agent需要周期性的執(zhí)行某項(xiàng)動(dòng)作,比如某個(gè)Agent需要定時(shí)從互聯(lián)網(wǎng)上抓取某些公開(kāi)數(shù)據(jù)以填充自身知識(shí)庫(kù),或者對(duì)本地?cái)?shù)據(jù)庫(kù)進(jìn)行操作和更新。對(duì)JADE來(lái)說(shuō),用TickerBehaviour很容易實(shí)現(xiàn),下面是一個(gè)周期性操作數(shù)據(jù)庫(kù)的簡(jiǎn)單例子。
package jade.capScoreAdopter; import jade.core.*; import jade.core.behaviours.*; import java.sql.*; import common.DataBaseConnection; public class IndustryScoreAdopt extends Agent { protected void adoptScore(){ Connection conn=null; CallableStatement proc=null; try{ conn=DataBaseConnection.getConnection(); proc=conn.prepareCall("{call P_WriteIndustryScore}"); proc.close(); conn.close(); } catch (SQLException e) { System.out.println("調(diào)用存儲(chǔ)過(guò)程出錯(cuò)!"); } } protected void setup() { System.out.println("Agent " + getLocalName() + " started."); addBehaviour(new TickerBehaviour(this, 1000000) {// 1000秒執(zhí)行一次 protected void onTick() { adoptScore(); System.out.println("Agent " + myAgent.getLocalName() + "執(zhí)行一次知識(shí)調(diào)整: tick=" + getTickCount()); } }); } } 附:創(chuàng)建數(shù)據(jù)庫(kù)連接類(lèi) package common; import java.sql.*; public class DataBaseConnection { public static Connection getConnection(){ Connection conn=null; // 連接數(shù)據(jù)庫(kù),sqlserver連接串 String CLASSFORNAME="com.microsoft.jdbc.sqlserver.SQLServerDriver"; String SERVANDDB="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=enterprisediagnose"; String USER="sa";//用戶(hù)和密碼 String PWD="sa"; try{ Class.forName(CLASSFORNAME); conn = java.sql.DriverManager.getConnection(SERVANDDB,USER,PWD); }catch(Exception e){ e.printStackTrace(); System.out.println("Error Trace in getConnection() : " + e.getMessage()); } return conn; } } [from http://blog./u/17663/showart_378411.html] |
|
來(lái)自: 苦修 > 《計(jì)算機(jī)編程》