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

简介: Spring相关的依赖导入进去,即可使用spring的定时任务! org.springframework spring-test 4.

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邮件是有限的,而且频繁的可能会被当成垃圾邮件,我只需要知道一条信息,某某服务器宕机了,一遍就可以,最后给我发三十遍,如此的话,大量的无效邮件很浪费资源,而且浪费时间。所以说,本文只是一个服务器监控小示例,实际开发中,切勿直接拿来用,最好要有相关的判断和逻辑。这样才能比较高效,达到预期期望。

 

目录
相关文章
|
2天前
|
Java 数据库 Spring
Spring Boot 实现定时任务的动态增删启停
Spring Boot 实现定时任务的动态增删启停
31 0
|
2天前
|
弹性计算 监控 网络协议
ecs资源监控操作
监控阿里云ECS服务器资源分为7步:登录阿里云控制台,进入ECS管理界面,选择要监控的实例,查看基础监控数据,通过云监控服务获取详细图表、配置报警规则,可选安装云监控插件获取OS级数据,最后定期审查优化资源配置。通过这些步骤,确保系统稳定运行并及时处理问题。如需帮助,参考官方文档或联系阿里云支持。
39 3
|
2天前
|
弹性计算 监控 数据可视化
ecs自定义监控
ecs自定义监控
29 1
|
2天前
|
Arthas 弹性计算 运维
阿里云ECS监控服务
阿里云ECS监控服务
424 2
|
2天前
|
druid Java 数据库
Spring Boot的定时任务与异步任务
Spring Boot的定时任务与异步任务
|
2天前
|
弹性计算 监控 数据可视化
ECS网络流量监控
ECS网络流量监控
85 2
|
2天前
|
弹性计算 运维 监控
ECS资源监控
ECS资源监控涉及CPU、内存、磁盘I/O、网络流量、系统负载和进程的关键指标,通过云服务商控制台、监控服务、API与SDK、运维工具进行实时监控和告警设置。支持历史数据查询、事件监控,以及使用Windows资源监视器和Linux系统工具进行操作系统层面监控。全面监控确保ECS实例稳定运行、资源有效利用和问题及时处理。如需特定云服务商的指导,请询问。
49 3
|
2天前
|
开发框架 监控 Java
深入探索Spring Boot的监控、管理和测试功能及实战应用
【5月更文挑战第14天】Spring Boot是一个快速开发框架,提供了一系列的功能模块,包括监控、管理和测试等。本文将深入探讨Spring Boot中监控、管理和测试功能的原理与应用,并提供实际应用场景的示例。
15 2
|
2天前
|
Java 调度 Maven
Springboot实战篇--Springboot框架通过@Scheduled实现定时任务
Spring Boot的Scheduled定时任务无需额外Maven依赖,通过`@EnableScheduling`开启。任务调度有两种方式:fixedRate和fixedDelay,前者任务结束后立即按设定间隔执行,后者在任务完成后等待设定时间再执行。更灵活的是cron表达式,例如`0 0 3 * * ?`表示每天3点执行。实现定时任务时,需注意默认单线程执行可能导致的任务交错,可通过自定义线程池解决。
|
2天前
|
Java API 数据安全/隐私保护
【亮剑】如何在Java项目中结合Spring框架实现邮件发送功能
【4月更文挑战第30天】本文介绍了如何在Java项目中结合Spring框架实现邮件发送功能。首先,需在`pom.xml`添加Spring和JavaMail依赖。然后,在`applicationContext.xml`配置邮件发送器,包括SMTP服务器信息。接着,创建一个使用依赖注入的`EmailService`类,通过`JavaMailSender`发送邮件。最后,调用`EmailService`的`sendSimpleEmail`方法即可发送邮件。最佳实践包括:使用配置管理敏感信息,利用`MimeMessage`构造复杂邮件,异常处理和日志记录,以及在大量发送时考虑使用邮件队列。