Send regular notifications with LineNotify + Spring Boot

at first

I want to be notified of specific information regularly when creating a web application with SpringBoot! !! !! As a result of investigating the method of thinking, I was able to implement it unexpectedly easily, so I summarized it.

Execution environment

① Get an access token on the LINE Notify official page

Access the URL below, read the displayed QR code, and add LINE Notify as a friend.

https://notify-bot.line.me/ja/

After that, after logging in with your LINE account on the same page, go to "My Page" → "Issue Access Token". Enter the token name (displayed at the top of the message when the message is actually notified on LINE) and select any talk room to display the token.

Please note that the token will be displayed *** once ***. However, you can issue as many as you like, so don't worry about that.

② Create a class to send notifications

Create a bean to register in the DI container to send notifications to LINE. There are no special dependencies required.

LineNotify.java



@Component
public class LineNotify {
    public void executeNotification() {
         String message = "Message you want to send";
         String token = "Obtained token";
        
	     sendNotification(message,token);
	}

	public void sendNotification(String message, String token) {
		HttpURLConnection connection = null;
		try {
			URL url = new URL("https://notify-api.line.me/api/notify");
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.addRequestProperty("Authorization", "Bearer " + token);
			try (OutputStream outputStream = connection.getOutputStream();
					PrintWriter writer = new PrintWriter(outputStream)) {
				writer.append("message=").append(URLEncoder.encode(message, "UTF-8")).flush();
			}
		} catch (Exception e) {
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
    }
}

Pass the message and token you want to send to the argument of the sendNotification method, and run POST communication to the specified URL. OAuth authentication is required to send notifications with LINE Notify, but authentication is executed by adding ʻAuthorization: Bearer <access_token>` to the request header in the method.

③ Settings for sending notifications on a regular basis

To enable the scheduled task execution function Use the @EnableScheduling annotation on the main class.

Application.java



@SpringBootApplication
@EnableScheduling //···add to
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

This allows you to discover any bean in a DI container that uses the @Scheduled annotation. So, go back to the class that implemented the notification function earlier, and add annotations to the methods that you actually want to execute periodically.

LineNotify.java



@Component
public class LineNotify {
    @Scheduled(cron = "0 * * * * *", zone = "Asia/Tokyo") //···add to
    public void executeNotification() {
         String message = "Message you want to send";
         String token = "Obtained token";
        
	     sendNotification(message,token);
	}

     ...

Once this is done, all you have to do is start the server and the task will be executed and you will be notified.

cron specifies the cycle for executing tasks, and zone specifies the time zone. From the left, cron can set triggers for" seconds, minutes, hours, months, days, days of the week ", and the sample code above is set to execute tasks at 0 seconds per minute. For example, if you want to execute a task every day at 9:00:00 Set something like " cron =" 0 0 9 * * * " ".

There are other options such as ʻinitialDelay that specifies the execution n seconds after the application starts, and fixedDelay` that specifies the execution n seconds after the execution of the method process is completed, so you can customize it relatively freely. can do.

reference

Notification by LINE Notify from Java implemented in 5 minutes ・ How to execute tasks regularly with Spring Boot

Recommended Posts

Send regular notifications with LineNotify + Spring Boot
Send email with spring boot
Download with Spring Boot
Asynchronous processing with regular execution in Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
[Spring Boot] Send an email
Create microservices with Spring Boot
Use Basic Authentication with Spring Boot
Create an app with Spring Boot 2
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Get validation results with Spring Boot
(Intellij) Hello World with Spring Boot
Create an app with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Message cooperation started with Spring Boot
Hello World with Eclipse + Spring Boot + Maven
Perform transaction confirmation test with Spring Boot
HTTPS with Spring Boot and Let's Encrypt
Try using Spring Boot with VS Code
Start web application development with Spring Boot
Launch Nginx + Spring Boot application with docker-compose
I tried Lazy Initialization with Spring Boot 2.2.0
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Asynchronous processing with Spring Boot using @Async
Implement paging function with Spring Boot + Thymeleaf
(IntelliJ + gradle) Hello World with Spring Boot
Use cache with EhCashe 2.x with Spring Boot
Form class validation test with Spring Boot
Run WEB application with Spring Boot + Thymeleaf
Achieve BASIC authentication with Spring Boot + Spring Security
Create a website with Spring Boot + Gradle (jdk1.8.x)
Configure Spring Boot application with maven multi module
Test controller with Mock MVC in Spring Boot
Create a simple search app with Spring Boot
Hash passwords with Spring Boot + Spring Security (with salt, with stretching)
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
Run Scala applications with Spring Boot through Gradle
How to use built-in h2db with spring boot
Hello world! With Spring Boot (Marven + text editor)
Try LDAP authentication with Spring Security (Spring Boot) + OpenLDAP