聚合全网技术文章,根据你的阅读喜好进行个性推荐
系统是用Spring+MyBais做的。现在要一个单独线程将从串口中读取的数据写入数据库。
程序写好的,不知道放哪,怎么启动
两种实现方式,一种是采用spring,现实InitializingBean,或者采用系统注册.注解@PostConstruct,两个都必须是web环境
package org.lichengmeng.thread; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.io.IOException; import java.io.InputStream; import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; @Component public class TempReadAndSave { @PostConstruct public void init() { try { (new TempReadAndSave()).connect("COM4"); } catch (Exception e) { e.printStackTrace(); } } void connect ( String portName ) throws Exception { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if ( portIdentifier.isCurrentlyOwned() ) { System.out.println("Error: Port is currently in use"); } else { CommPort commPort = portIdentifier.open(this.getClass().getName(),2000); if ( commPort instanceof SerialPort ) { SerialPort serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(4800,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); InputStream in = serialPort.getInputStream(); (new Thread(new SerialReader(in))).start(); } else { System.out.println("Error: Only serial ports are handled by this example."); } } } /** */ public static class SerialReader implements Runnable { InputStream in; public SerialReader ( InputStream in ) { this.in = in; } public void run () { int data[] = new int[8]; float temp,decade,unit; int i = 0; try { while (true) { data[i++] = in.read(); if(i>=7) { for( int j=0; j<7 ;j++) { if((data[j] == -1) && (j+1 <= 6) && (data[j+1] != -1)) { decade = Integer.valueOf(Integer.toHexString(data[++j])); unit = Integer.valueOf(Integer.toHexString(data[++j])); temp = decade + unit/10; //dao操作 System.out.println(temp); } } i=0; } } } catch ( IOException e ) { e.printStackTrace(); }finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
其实有很多方法,介绍一种简单的,就是写监听器,具体
<listener> <display-name>initListener</display-name> <listener-class>XXX.InitServlet</listener-class> </listener>
public class InitServlet implements ServletContextListener { private static Logger logger = LoggerFactory.getLogger(InitServlet.class); @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent arg0) { //写你的代码 }
不用,注解成Bean就可以了,然后在一个方法中加一个PostConstruct注解,使用这个方法启动线程就可以了。
Spring 有一个Scheduled的annotation~
参考如下:
https://spring.io/guides/gs/scheduling-tasks/
两种实现方式,一种是采用spring,现实InitializingBean,或者采用系统注册.注解@PostConstruct,两个都必须是web环境
引用来自“StateGrace”的评论
两种实现方式,一种是采用spring,现实InitializingBean,或者采用系统注册.注解@PostConstruct,两个都必须是web环境
其实有很多方法,介绍一种简单的,就是写监听器,具体
不用,注解成Bean就可以了,然后在一个方法中加一个PostConstruct注解,使用这个方法启动线程就可以了。
Spring 有一个Scheduled的annotation~
参考如下:
https://spring.io/guides/gs/scheduling-tasks/