cuốn sách gpt4 ai đã làm

Spring ScheduledTask - hỗ trợ bắt đầu/dừng?

In lại Tác giả: Taklimakan Thời gian cập nhật: 2023-11-03 04:26:16 hai mươi bốn 4
mua khóa gpt4 Nike

Có cách nào để bắt đầu hoặc dừng tác vụ được lên lịch bằng cách sử dụng tác vụ theo lịch trình Spring được khởi tạo bằng tệp ngữ cảnh hoặc chú thích @Scheduled không?

Tôi muốn bắt đầu tác vụ khi cần và dừng nó khi không cần chạy tác vụ đó nữa.

Nếu điều này là không thể, các lựa chọn thay thế cho việc đưa các biến lò xo vào luồng là gì?

câu trả lời hay nhất

Dưới đây là ví dụ về phương pháp lập lịch bắt đầu/dừng trong Spring Boot. Bạn có thể sử dụng API như thế này:
http:localhost:8080/bắt đầu - Bắt đầu các phương thức theo lịch trình ở tốc độ cố định 5000 mili giây
http:localhost:8080/stop - Phương pháp dừng kế hoạch

nhập org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
nhập org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
nhập org.springframework.context.annotation.ComponentScan;
nhập org.springframework.context.annotation.Configuration;
nhập org.springframework.http.HttpStatus;
nhập org.springframework.http.ResponseEntity;
nhập org.springframework.scheduling.TaskScheduler;
nhập org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
nhập org.springframework.stereotype.Controller;
nhập org.springframework.web.bind.annotation.RequestMapping;
nhập java.time.Instant;
nhập java.util.concurrent.ScheduredFuture;

@Cấu hình
@ComponentScan
@EnableAutoConfiguration
lớp công khai TaskSchedulingApplication {

public static void main(String[] args) {
SpringApplication.run(TaskSchedulingApplication.class, args);
}

@Bean
Chủ đề TaskSchedulerPoolTaskScheduler() {
trả về ThreadPoolTaskScheduler mới();
}
}

@Controller
lớp ScheduleController {

cuối cùng tĩnh công khai dài FIXED_RATE = 5000;

@Autowired
Trình lập lịch tác vụ Trình lập lịch tác vụ;

ScheduledFuture ScheduledFuture;

@RequestMapping("bắt đầu")
ResponseEntity bắt đầu() {
theo lịch trìnhFuture = taskScheduler.scheduleAtFixedRate(printHour(), FIXED_RATE);

trả về ResponseEntity(HttpStatus.OK) mới;
}

@RequestMapping("dừng")
ResponseEntity dừng() {
theo lịch trìnhFuture.cancel(false);
trả về ResponseEntity(HttpStatus.OK) mới;
}

riêng tư Runnable printHour() {
return () -> System.out.println("Xin chào " + Instant.now().toEpochMilli());
}

}

Spring ScheduledTask - hỗ trợ bắt đầu/dừng? Về java - Spring ScheduledTask - hỗ trợ bắt đầu/dừng? , chúng tôi đã tìm thấy một câu hỏi tương tự trên Stack Overflow: https://stackoverflow.com/questions/7107420/

hai mươi bốn 4 0
Taklimakan
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress