Spring定时任务使用及如何使用邮件监控服务器

作者:挑战者V 时间:2023-01-12 16:38:58 

Spring相关的依赖导入进去,即可使用spring的定时任务!


<!-- spring核心包 -->
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-test</artifactId>
     <version>4.3.13.RELEASE</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>4.3.13.RELEASE</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-core</artifactId>
     <version>4.3.13.RELEASE</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-aop</artifactId>
     <version>4.3.13.RELEASE</version>
   </dependency>

定时任务是开发中常用的,比如订单查询,一位客人订购的某个东西,但是尚未支付,超过订单时效期自动失效,那么又是怎么样知道订单的时效性过呢?定时任务,可以每分钟或者每秒钟进行查询。

定时任务的应用是非常广的,下面应用下监控服务器,虽然说现在开源监控软件挺多的,什么zabbix,nagios或者其他等等。下面我将使用代码监控服务器:

首先准备邮件的依赖:


<!-- 发邮件 -->      
   <dependency>
     <groupId>com.sun.mail</groupId>
     <artifactId>javax.mail</artifactId>
     <version>1.5.2</version>
     <scope>provided</scope>
   </dependency>

邮件工具类:


import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {

public static void sendMail(String email, String emailMsg)
     throws AddressException, MessagingException {
   // 1.创建一个程序与邮件服务器会话对象 Session

Properties props = new Properties();
   props.setProperty("mail.transport.protocol", "SMTP");
   props.setProperty("mail.host", "smtp.163.com");
   props.setProperty("mail.smtp.auth", "true");// 指定验证为true

// 创建验证器
   Authenticator auth = new Authenticator() {
     public PasswordAuthentication getPasswordAuthentication() {
       return new PasswordAuthentication("123@163.com", "123");
     }
   };

Session session = Session.getInstance(props, auth);

// 2.创建一个Message,它相当于是邮件内容
   Message message = new MimeMessage(session);

message.setFrom(new InternetAddress("123@163.com")); // 设置发送者

message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者

message.setSubject("邮件告警");

message.setContent(emailMsg, "text/html;charset=utf-8");

// 3.创建 Transport用于将邮件发送

Transport.send(message);

}

}

监控服务器类:


package cn.pms.monitor;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import cn.pms.util.MailUtils;

public class MonitorUrl {

public static void testUrlWithTimeOut2016(String urlString,int timeOutMillSeconds){
   long lo = System.currentTimeMillis();
   URL url;  
   try {  
      url = new URL(urlString);  
      URLConnection co = url.openConnection();
      co.setConnectTimeout(timeOutMillSeconds);
      co.connect();
      System.out.println("连接可用");  
   } catch (Exception e1) {  
      System.out.println("连接打不开!");  
      url = null;  
      emailMonitor2016();
   }  
   System.out.println(System.currentTimeMillis()-lo);
 }

public static void testUrlWithTimeOut2018(String urlString,int timeOutMillSeconds){
   long lo = System.currentTimeMillis();
   URL url;  
   try {  
      url = new URL(urlString);  
      URLConnection co = url.openConnection();
      co.setConnectTimeout(timeOutMillSeconds);
      co.connect();
      System.out.println("连接可用");  
   } catch (Exception e1) {  
      System.out.println("连接打不开!");  
      url = null;  
      emailMonitor2018();
   }  
   System.out.println(System.currentTimeMillis()-lo);
 }

public static void testUrlWithTimeOut1818(String urlString,int timeOutMillSeconds){
   long lo = System.currentTimeMillis();
   URL url;  
   try {  
      url = new URL(urlString);  
      URLConnection co = url.openConnection();
      co.setConnectTimeout(timeOutMillSeconds);
      co.connect();
      System.out.println("连接可用");  
   } catch (Exception e1) {  
      System.out.println("连接打不开!");  
      url = null;  
      emailMonitor1818();;
   }  
   System.out.println(System.currentTimeMillis()-lo);
 }

public static void testUrlWithTimeOut1616(String urlString,int timeOutMillSeconds){
   long lo = System.currentTimeMillis();
   URL url;  
   try {  
      url = new URL(urlString);  
      URLConnection co = url.openConnection();
      co.setConnectTimeout(timeOutMillSeconds);
      co.connect();
      System.out.println("连接可用");  
   } catch (Exception e1) {  
      System.out.println("连接打不开!");  
      url = null;  
      emailMonitor1616();
   }  
   System.out.println(System.currentTimeMillis()-lo);
 }

public static void emailMonitor2016() {
   try {
     MailUtils.sendMail("123@qq.com", "tomcat服务器端口为2016宕机了");
   } catch (AddressException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (MessagingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }

public static void emailMonitor2018() {
   try {
     MailUtils.sendMail("123@qq.com", "tomcat服务器端口为2018宕机了");
   } catch (AddressException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (MessagingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }

public static void emailMonitor1818() {
   try {
     MailUtils.sendMail("1236@qq.com", "tomcat服务器端口为1818宕机了");
   } catch (AddressException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (MessagingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }

public static void emailMonitor1616() {
   try {
     MailUtils.sendMail("123@qq.com", "tomcat服务器端口为1616宕机了");
   } catch (AddressException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (MessagingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
}

具体定时任务类:


@Component
public class QuartzJob {

private static Logger logger = Logger.getLogger(QuartzJob.class);

@Scheduled(cron = "0 0/1 * * * ? ")
 public void test() {
   MonitorUrl.testUrlWithTimeOut2018("http://www.yc520.com:2018/", 2000);

MonitorUrl.testUrlWithTimeOut1616("http://www.yc520.com:1616/", 2000);
   logger.info("每分钟执行" + System.currentTimeMillis());
 }

@Scheduled(cron = "0 10 0 * * ?")
 public void monitorServerTest() {

System.out.println("每10分钟监控一次2018服务器和1616服务器");
   MonitorUrl.testUrlWithTimeOut2018("http://www.yc520.com:2018/", 2000);
   MonitorUrl.testUrlWithTimeOut1616("http://www.yc520.com:1616/", 2000);
 }

@Scheduled(cron="0 30 0 * * ?")
 public void monitorServer() {
   System.out.println("每30分钟监控一次1818测试服务器");
   MonitorUrl.testUrlWithTimeOut1818("http://www.yc520:1818/", 2000);
 }

}

由此就可以达到监控服务器的目的,当然这只是小试牛刀,而且也不够全面,当然也存在问题,如果是每分钟定时任务检测,突然一台服务器挂了,那么将会源源不断的发送邮件,163邮件是有限的,而且频繁的可能会被当成垃圾邮件,我只需要知道一条信息,某某服务器宕机了,一遍就可以,最后给我发三十遍,如此的话,大量的无效邮件很浪费资源,而且浪费时间。

所以说,本文只是一个服务器监控小示例,实际开发中,切勿直接拿来用,最好要有相关的判断和逻辑。这样才能比较高效,达到预期期望。

来源:https://www.cnblogs.com/youcong/p/9037425.html

标签:spring,定时,任务,邮件,监控,服务器
0
投稿

猜你喜欢

  • 使用Java程序模拟实现新冠病毒传染效果

    2022-09-12 20:26:14
  • Spring Boot集成Ehcache缓存解决方式

    2023-05-13 08:27:27
  • resty upload无需依赖的文件上传与下载

    2023-01-17 14:54:31
  • Spring Boot FeignClient 如何捕获业务异常信息

    2022-01-26 11:57:41
  • Java使用Gateway自定义负载均衡过滤器

    2022-06-27 03:55:09
  • C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    2022-09-14 20:41:14
  • mybatis多个区间处理方式(双foreach循环)

    2023-11-26 09:01:42
  • Springboot+AOP实现返回数据提示语国际化的示例代码

    2021-08-18 19:49:12
  • Android中AutoCompleteTextView自动提示

    2022-06-21 19:07:36
  • Android项目实现短信的发送、接收和对短信进行拦截

    2021-06-14 06:59:26
  • 利用Java读取二进制文件实例详解

    2023-07-27 03:25:42
  • Java8中Stream的一些神操作

    2021-11-18 19:07:21
  • Java try()语句实现try-with-resources异常管理机制操作

    2022-02-06 18:29:16
  • Java实现自动压缩文件并加密的方法示例

    2023-05-08 03:33:18
  • ListView实现聊天列表之处理不同数据项

    2022-07-01 01:06:58
  • C# Winform 实现控件自适应父容器大小的示例代码

    2021-06-15 20:00:52
  • 总结Java对象被序列化的两种方法

    2023-05-11 09:46:52
  • Java实现批量导入excel表格数据到数据库中的方法

    2021-06-22 07:39:49
  • java中Hashmap的get方法使用

    2023-10-29 13:10:05
  • SpringBoot中的PUT和Delete请求使用

    2022-01-22 19:33:32
  • asp之家 软件编程 m.aspxhome.com