Java tutorial
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sample; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.jms.*; import java.math.BigInteger; import java.security.SecureRandom; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; @Controller public class TimeController { private final Logger log = LoggerFactory.getLogger(TimeController.class); @Autowired private ConnectionFactory jmsFactory; @RequestMapping(method = RequestMethod.GET, value = { "/tick" }) public ModelAndView get() throws Exception { Connection connection = jmsFactory.createConnection(); Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); SecureRandom srandom = new SecureRandom(); String rand = new BigInteger(176, srandom).toString(32); String q = Long.toString(System.currentTimeMillis()) + "-" + rand; Destination destination = jmsSession.createQueue(q); Timer timer = new Timer(); long delay = 1 * 1000; timer.schedule(new TickTask(jmsSession, destination), 0, delay); ModelAndView mav = new ModelAndView("client"); mav.addObject("queue", destination.toString()); return mav; } private class TickTask extends TimerTask { private Destination destination; private Session session; private MessageProducer producer; TickTask(Session s, Destination d) throws JMSException { this.destination = d; this.session = s; this.producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } @Override public void run() { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss"); String current_time = format.format(date); log.info("Destination : " + destination.toString() + ", time : " + current_time); try { TextMessage message = session.createTextMessage(current_time); producer.send(message); } catch (JMSException e) { e.printStackTrace(); } } } }