### start() Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/executor-api.md Initializes and starts the executor. This involves validating configuration, setting up directories, establishing connections, and starting background threads and the HTTP server. ```APIDOC ## start() ### Description Initializes and starts the executor. This method validates required configuration, initializes the job log directory, builds admin client connections, starts background threads, starts the embedded HTTP server, and starts the executor registry thread. ### Method ```java public void start() throws Exception ``` ### Throws: - `RuntimeException` - if validation fails or required config is missing ### Usage Example: ```java XxlJobExecutor executor = new XxlJobExecutor(); executor.setAdminAddresses("http://localhost:8080"); executor.setAppname("my-executor"); executor.setAccessToken("default"); executor.setIp("192.168.1.100"); executor.setPort(9999); executor.start(); ``` ``` -------------------------------- ### Install Node.js Interpreter Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/errors.md Use this command to install Node.js if it's not already present on your system, typically required for Node.js-based jobs. ```bash # For Node.js jobs apt-get install nodejs ``` -------------------------------- ### Start Executor Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/executor-api.md Initializes and starts the XXL-Job executor. Ensure all required configurations like adminAddresses, appname, and accessToken are set before calling. ```java public void start() throws Exception ``` ```java XxlJobExecutor executor = new XxlJobExecutor(); executor.setAdminAddresses("http://localhost:8080"); executor.setAppname("my-executor"); executor.setAccessToken("default"); executor.setIp("192.168.1.100"); executor.setPort(9999); executor.start(); ``` -------------------------------- ### Start and Stop XXL-JOB with Docker Compose Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB官方文档.md Commands to start and stop the XXL-JOB services using Docker Compose. Assumes the .env file in the ./docker directory is configured. ```bash // 启动 docker compose up -d // 停止 docker compose down ``` -------------------------------- ### Install Python Interpreter Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/errors.md Use this command to install Python 3 if it's not already present on your system, typically required for Python-based jobs. ```bash # For Python jobs apt-get install python3 ``` -------------------------------- ### XXL-JOB Integration & Usage Guides Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/MANIFEST.md This section covers the integration and usage documentation for XXL-JOB, including a comprehensive integration guide and the main README file. ```APIDOC ## Integration & Usage Guides This section covers the integration and usage documentation for XXL-JOB, including a comprehensive integration guide and the main README file. ### integration-guide.md - **Description**: The most comprehensive guide, detailing a 5-step Spring Boot quick start, advanced patterns, deployment strategies, testing, monitoring, debugging, and security for XXL-JOB. - **Content**: 5-step Spring Boot quick start, Advanced patterns (sharding, broadcast, init/destroy, timeout, retry, dependencies), Deployment patterns (dev, production, Docker/K8s, HA), Testing strategies (unit, integration), Monitoring, debugging, and security. ### README.md - **Description**: The main README file serves as a navigation hub, providing project overview, architecture, quick start paths by audience, file structure, and common task examples. - **Content**: Project overview and key concepts, Architecture diagram and design patterns, Quick navigation by audience (new users, developers, ops), File structure and getting started guides, Common tasks with code examples. ``` -------------------------------- ### Docker Compose Startup Steps for XXL-JOB Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB-English-Documentation.md Steps to download, build, and start XXL-JOB using Docker Compose. Ensure MySQL data persistence directory is customized. ```bash // Download XXL-JOB git clone --branch "$(curl -s https://api.github.com/repos/xuxueli/xxl-job/releases/latest | jq -r .tag_name)" https://github.com/xuxueli/xxl-job.git // Build XXL-JOB mvn clean package -Dmaven.test.skip=true // Start XXL-JOB MYSQL_PATH={自定义数据库持久化目录} docker compose up -d // Stop XXL-JOB docker compose down ``` -------------------------------- ### Example: Handling Job Success Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Demonstrates how to log processing steps and then mark the job as successful with a custom message indicating the number of items processed. ```java @XxlJob("successExample") public void successExample() { XxlJobHelper.log("Starting data processing"); int processed = processData(); XxlJobHelper.log("Processed {} items", processed); XxlJobHelper.handleSuccess("Processed " + processed + " items"); } ``` -------------------------------- ### Broadcast Job Execution Example Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Demonstrates how to use shard index and total to distribute work across multiple executors for broadcast tasks. ```java @XxlJob("broadcastJobHandler") public void broadcastJobHandler() { int shardIndex = XxlJobHelper.getShardIndex(); // e.g., 0 int shardTotal = XxlJobHelper.getShardTotal(); // e.g., 3 // Process 1/3 of data on each executor List allItems = loadAllItems(); for (int i = shardIndex; i < allItems.size(); i += shardTotal) { processItem(allItems.get(i)); } } ``` -------------------------------- ### Basic Job Handler Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Implement a simple job that logs its start and end, handling success or failure with messages. ```java @XxlJob("basicJob") public void basicJob() { XxlJobHelper.log("Job started"); try { // Job logic here int result = doWork(); XxlJobHelper.log("Work completed: {}", result); XxlJobHelper.handleSuccess("Completed with result: " + result); } catch (Exception e) { XxlJobHelper.log(e); XxlJobHelper.handleFail("Failed: " + e.getMessage()); } } ``` -------------------------------- ### Python Example: Triggering an XXL-Job Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/openapi-reference.md This Python script demonstrates how to trigger an XXL-Job by sending a POST request to the executor's run endpoint. Ensure you have the 'requests' library installed. The payload includes job details, execution parameters, and authentication headers. ```python import requests import json import time def trigger_job(executor_address, job_id, handler_name): payload = { "jobId": job_id, "executorHandler": handler_name, "executorParams": "", "executorBlockStrategy": "SERIAL_EXECUTION", "executorTimeout": 300, "logId": 12345, "logDateTime": int(time.time() * 1000), "glueType": "BEAN", "broadcastIndex": 0, "broadcastTotal": 1 } headers = { "XXL-JOB-ACCESS-TOKEN": "default", "XXL-JOB-APPNAME": "my-executor" } response = requests.post( f"{executor_address}/run?action=trigger", json=payload, headers=headers ) return response.json() ``` -------------------------------- ### Start Job Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB官方文档.md Starts or enables a job, initiating its scheduling. Requires the job ID in the request body. ```APIDOC ## POST /api/startJob ### Description Starts or enables a job, initiating its scheduling. ### Method POST ### Endpoint {调度中心根地址}/api/startJob ### Headers - **XXL-JOB-ACCESS-TOKEN** (string) - Required - Request token - **XXL-JOB-APPNAME** (string) - Required - Executor AppName ### Request Body - **id** (integer) - Required - Job ID ### Request Example ```json { "id":1 } ``` ### Response #### Success Response (200) - **code** (integer) - 200 indicates normal, others indicate failure - **msg** (null) - Error message ``` -------------------------------- ### Initialize XxlJobExecutor Before Use Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/errors.md Ensure the XxlJobExecutor is properly initialized with start() before accessing its singleton instance. This prevents errors related to uninitialized executors. ```java XxlJobExecutor executor = new XxlJobExecutor(); executor.setAdminAddresses("http://localhost:8080"); executor.start(); // Must be called before getInstance() // Now safe to call XxlJobExecutor instance = XxlJobExecutor.getInstance(); ``` -------------------------------- ### Example: Handling Job Failure Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Illustrates handling potential failures, such as a null value, by logging the error and calling handleFail with a descriptive message. It also shows how to catch exceptions and report them. ```java @XxlJob("failExample") public void failExample() { try { String value = getValue(); if (value == null) { XxlJobHelper.handleFail("Required value not found"); return; } // process value XxlJobHelper.handleSuccess(); } catch (Exception e) { XxlJobHelper.log(e); XxlJobHelper.handleFail("Exception: " + e.getMessage()); } } ``` -------------------------------- ### Docker Compose Setup and Management Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB官方文档.md This sequence of shell commands outlines the steps to clone, build, configure, and manage an XXL-JOB cluster using Docker Compose. It includes downloading the latest release, building the project, configuring environment variables, and starting/stopping the services. ```bash // 下载 XXL-JOB git clone --branch "$(curl -s https://api.github.com/repos/xuxueli/xxl-job/releases/latest | jq -r .tag_name)" https://github.com/xuxueli/xxl-job.git // 构建 XXL-JOB mvn clean package -Dmaven.test.skip=true // 配置 XXL-JOB(前往docker目录,自定义 .env) cd ./docker cat .env // 启动 XXL-JOB docker compose up -d // 停止 XXL-JOB docker compose down ``` -------------------------------- ### IJobHandler.init() Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/handler-api.md The `init` method is a lifecycle hook that is invoked once when the JobThread for this handler is created. It is suitable for resource allocation and setup. ```APIDOC ## init() ### Description Lifecycle hook invoked once when the JobThread for this handler is created. Use this for resource allocation, connection pooling, or caching. ### Signature `void init() throws Exception` ### Called Once per job thread initialization ### Default No-op implementation ### Exceptions Logged; do not prevent handler execution ``` -------------------------------- ### log() Response (Partial Log) Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/openapi-reference.md Example of a partial log response from the log() method. Includes log content and indicates if it's the end of the log. ```json { "code": 200, "msg": "", "content": { "fromLineNum": 0, "toLineNum": 99, "logContent": "2023-01-01 12:00:00 [JobThread-5] Job started...\n...", "isEnd": false } } ``` -------------------------------- ### Get Admin Biz List - Java Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/executor-api.md Returns a list of admin client proxies used for RPC calls to all configured admin instances. ```java public List getAdminBizList() ``` ```java List adminList = executor.getAdminBizList(); for (AdminBiz admin : adminList) { admin.callback(callbackRequest); } ``` -------------------------------- ### HTTP Job Handler Parameters Example Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB官方文档.md This JSON object demonstrates the comprehensive parameters that can be configured for the HTTP job handler, including URL, method, content type, headers, cookies, timeout, request body, form data, and authentication. ```json { "url": "http://www.baidu.com", "method": "POST", "contentType": "application/json", "headers": { "header01": "value01" }, "cookies": { "cookie01": "value01" }, "timeout": 3000, "data": "request body data", "form": { "key01": "value01" }, "auth": "auth data" } ``` -------------------------------- ### Development Configuration (Single Executor) Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/integration-guide.md Use this properties file for local development with a single executor instance. Ensure the admin addresses and executor port are correctly set for your local setup. ```properties xxl.job.admin.addresses=http://localhost:8080 xxl.job.executor.appname=dev-executor xxl.job.executor.accessToken=default xxl.job.executor.port=9999 xxl.job.executor.logpath=/tmp/xxl-job ``` -------------------------------- ### XXL-Job Executor Request Routing Examples Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/openapi-reference.md The embed server in the executor routes incoming HTTP POST requests to specific methods based on the 'action' query parameter. ```http POST {executorAddress}/run?action=beat → beat() POST {executorAddress}/run?action=idleBeat → idleBeat() POST {executorAddress}/run?action=trigger → trigger() POST {executorAddress}/run?action=kill → kill() POST {executorAddress}/run?action=log → log() ``` -------------------------------- ### Usage Example of @XxlJob Annotation Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/handler-api.md Demonstrates how to apply the @XxlJob annotation to methods within a Spring component to register them as job handlers. ```java @Component public class JobHandlers { @XxlJob("demoJobHandler") public void demoJobHandler() throws Exception { XxlJobHelper.log("Job executing"); XxlJobHelper.handleSuccess(); } @XxlJob("demoJobHandlerWithInit") public void demoJobHandlerWithInit() throws Exception { XxlJobHelper.log("Job executing"); XxlJobHelper.handleSuccess(); } public void init() { System.out.println("Init called"); } } ``` -------------------------------- ### Configure Admin Addresses for Executor Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/errors.md Set the admin addresses for the XXL-JOB executor before calling start(). This is crucial for the executor to connect to the admin console. ```java executor.setAdminAddresses("http://localhost:8080"); executor.start(); ``` -------------------------------- ### Job with Init and Destroy Methods Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/integration-guide.md Manage resources like database connections or caches using init and destroy methods. The init method is called when the job thread starts, and the destroy method is called when it terminates. ```java @Component public class DatabaseJobHandler { private DataSource dataSource; @XxlJob(value = "dbJob", init = "initDB", destroy = "closeDB") public void dbJob() throws Exception { XxlJobHelper.log("Executing DB job"); try (Connection conn = dataSource.getConnection()) { // Use connection XxlJobHelper.handleSuccess(); } } // Called once when job thread is created public void initDB() { XxlJobHelper.log("Initializing database connection pool"); // Setup resource } // Called when job thread is destroyed public void closeDB() { XxlJobHelper.log("Closing database connection pool"); // Cleanup resource } } ``` -------------------------------- ### log() Response (Final Log Chunk) Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/openapi-reference.md Example of the final log chunk response from the log() method. The 'isEnd' flag is true. ```json { "code": 200, "msg": "", "content": { "fromLineNum": 100, "toLineNum": 150, "logContent": "...Job completed\n", "isEnd": true } } ``` -------------------------------- ### Implement Custom Job Logic with IJobHandler Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/handler-api.md Example of implementing a custom job handler by extending IJobHandler and overriding the execute method. Use XxlJobHelper for logging and status updates. ```java public class MyJobHandler extends IJobHandler { @Override public void execute() throws Exception { XxlJobHelper.log("Job started"); // job logic here XxlJobHelper.handleSuccess("Job completed"); } } ``` -------------------------------- ### Standalone Executor Configuration Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/configuration.md Configure and start an XXL-Job executor programmatically in a standalone Java application. This includes setting admin addresses, app name, port, log path, and registering job handlers. ```java public class JobExecutorApp { public static void main(String[] args) throws Exception { // Create executor XxlJobExecutor executor = new XxlJobExecutor(); // Configure executor.setAdminAddresses("http://localhost:8080"); executor.setAppname("my-executor"); executor.setAccessToken("default"); executor.setPort(9999); executor.setLogPath("/var/log/xxl-job"); executor.setLogRetentionDays(7); // Start executor.start(); // Register handlers executor.registryJobHandler("job1", new MyJobHandler()); executor.registryJobHandler("job2", new MyJobHandler2()); // Keep running Thread.currentThread().join(); // Cleanup on shutdown Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { executor.destroy(); } catch (Exception e) { e.printStackTrace(); } })); } } ``` -------------------------------- ### Docker Compose Environment Variables Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/configuration.md Example of setting XXL-Job configuration via environment variables in a Docker Compose file. This is useful for injecting secrets and connection details. ```yaml environment: - XXL_JOB_TOKEN=my-secret-token - xxl.job.admin.addresses=http://xxl-job-admin:8080 ``` -------------------------------- ### Signaling Job Status with XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/handler-api.md Provides examples of using `XxlJobHelper` methods to explicitly signal the outcome of a job execution. These methods allow handlers to report success, failure, or timeout, optionally with a message. Unhandled exceptions are automatically treated as failures. ```java XxlJobHelper.handleSuccess() XxlJobHelper.handleSuccess(String msg) XxlJobHelper.handleFail() XxlJobHelper.handleFail(String msg) XxlJobHelper.handleTimeout() XxlJobHelper.handleTimeout(String msg) XxlJobHelper.handleResult(int code, String msg) ``` -------------------------------- ### idleBeat() Response (Failure - Not Idle) Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/openapi-reference.md Example of a failure response from idleBeat() when the job is not idle. Returns code 500. ```json { "code": 500, "msg": "job thread is running or has trigger queue.", "content": "" } ``` -------------------------------- ### Enable Verbose Logging with Logback Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/errors.md Configure the logback.xml file to set the logging level for the xxl-job core to DEBUG for more detailed output. ```xml ``` -------------------------------- ### idleBeat() Response (Success - Idle) Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/openapi-reference.md Example of a successful response from idleBeat() when the job is idle. Returns code 200. ```json { "code": 200, "msg": "", "content": "" } ``` -------------------------------- ### Configure XxlJob Executor via Properties Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/configuration.md Use this format for application.properties files to set up the XxlJob executor. It includes essential and optional parameters for connecting to the admin center and configuring executor behavior. ```properties # Admin center configuration xxl.job.admin.addresses=http://localhost:8080 # Executor configuration xxl.job.executor.appname=my-executor xxl.job.executor.accessToken=default # Optional: Network xxl.job.executor.ip= xxl.job.executor.port=9999 xxl.job.executor.address= # Optional: Timeout xxl.job.executor.timeout=3 # Optional: Logging xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler xxl.job.executor.logretentiondays=30 # Optional: GLUE xxl.job.executor.glueEnabled=true ``` -------------------------------- ### Get Log Timestamp with XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Retrieves the execution timestamp in milliseconds since the epoch. Returns -1 if not available. ```java public static long getLogDateTime() ``` -------------------------------- ### Configure Schedule Center Properties Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB-English-Documentation.md Configure the application.properties file for the xxl-job-admin to set up database connections, email alarms, login credentials, and communication tokens. ```properties ### JDBC connection info of schedule center:keep Consistent with chapter 2.1 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root_pwd spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ### Alarm mailbox spring.mail.host=smtp.qq.com spring.mail.port=25 spring.mail.username=xxx@qq.com spring.mail.from=xxx@qq.com spring.mail.password=xxx spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory ### Login account xxl.job.login.username=admin xxl.job.login.password=123456 ### TOKEN used for communication between the executor and schedule center, enabled if it’s not null xxl.job.accessToken= ### Internationalized Settings, the default is Chinese version,Switch to English when the value is "en". xxl.job.i18n=zh_CN ``` -------------------------------- ### Get Executor Registry Thread Helper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/executor-api.md Retrieves the registry thread helper used for periodic executor registration. ```java public ExecutorRegistryThreadHelper getExecutorRegistryThreadHelper() ``` -------------------------------- ### Build XXL-JOB Project Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB官方文档.md Builds the entire XXL-JOB project using Maven. The command skips running tests to speed up the build process. ```bash // 注意:如下命令需要在项目仓库根目录执行 mvn clean package -Dmaven.test.skip=true ``` -------------------------------- ### Get Log ID with XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Retrieves the unique identifier for the current job's log. Returns -1 if not available. ```java public static long getLogId() ``` -------------------------------- ### Configure Application Properties Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/integration-guide.md Configure XXL-JOB properties in your application.properties file. ```properties xxl.job.admin.addresses=http://localhost:8080 xxl.job.executor.appname=my-app xxl.job.executor.accessToken=default xxl.job.executor.logpath=/data/applogs/xxl-job ``` -------------------------------- ### Unit Test Job Handler in Java Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/integration-guide.md Demonstrates how to unit test a job handler by mocking the XxlJobContext and executing the handler's logic. Ensure to set and clear the context properly. ```java public class JobHandlersTest { private JobHandlers handlers; @BeforeEach public void setup() { handlers = new JobHandlers(); } @Test public void testHelloJob() throws Exception { // Mock XxlJobContext XxlJobContext context = new XxlJobContext( 1, "param", 100, System.currentTimeMillis(), "/tmp/test.log", 0, 1 ); XxlJobContext.setXxlJobContext(context); try { // Execute handlers.helloJob(); // Verify assertEquals(200, context.getHandleCode()); } finally { XxlJobContext.setXxlJobContext(null); } } } ``` -------------------------------- ### Get Trigger Callback Thread Helper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/executor-api.md Retrieves the callback thread helper for sending result callbacks to the admin center. ```java public TriggerCallbackThreadHelper getTriggerCallbackThreadHelper() ``` -------------------------------- ### Get Log File Name with XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Retrieves the absolute path to the job execution log file. Returns null if not available. ```java public static String getLogFileName() ``` -------------------------------- ### Verify Shell Interpreter Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/errors.md This command checks if the bash shell interpreter is installed and accessible in your system's PATH, which is standard for shell jobs. ```bash # For Shell jobs (bash should be standard) which bash ``` -------------------------------- ### Get Job ID with XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Retrieves the unique identifier for the current job execution. Returns -1 if called outside of a job context. ```java long jobId = XxlJobHelper.getJobId(); ``` -------------------------------- ### XxlJobContext Constructor Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/handler-api.md Illustrates the parameters used to construct the `XxlJobContext` object, which holds information about the current job execution. This context is automatically set up by the job thread. ```java XxlJobContext context = new XxlJobContext( jobId, // long: unique job ID jobParam, // String: job parameters logId, // long: log identifier logDateTime, // long: execution timestamp logFileName, // String: path to log file shardIndex, // int: broadcast/shard index (0-based) shardTotal // int: total broadcast/shard count ); ``` -------------------------------- ### Get XxlJobExecutor Singleton Instance Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/executor-api.md Retrieves the singleton instance of the XxlJobExecutor. This method should be called after the executor has been initialized. It throws a RuntimeException if the executor has not been initialized. ```java public static XxlJobExecutor getInstance() ``` -------------------------------- ### LogRequest DTO Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/types.md Request object for retrieving log entries of a specific job execution. Requires log ID, timestamp, and starting line number. ```java public class LogRequest implements Serializable { private long logId; private long logDateTime; private int fromLineNum; public LogRequest() { } public LogRequest(long logId, long logDateTime, int fromLineNum) { ... } public long getLogId() { return logId; } public long getLogDateTime() { return logDateTime; } public int getFromLineNum() { return fromLineNum; } // Setters omitted } ``` -------------------------------- ### Monitor Executor Startup with Netstat and Curl Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/errors.md Check if the executor is listening on its default port (9999) and verify its reachability to the admin server. ```bash # Check if executor is listening netstat -tlnp | grep 9999 ``` ```bash # Check if admin is reachable curl -H "XXL-JOB-ACCESS-TOKEN: default" \ -H "XXL-JOB-APPNAME: my-executor" \ -X POST http://localhost:8080/api/beat ``` -------------------------------- ### XXL-JOB Core Reference Documentation Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/MANIFEST.md This section details the core reference documentation files available for the xxl-job-core module. These files cover API references for executors and handlers, context helpers, type definitions, OpenAPI specifications, configuration details, and error codes. ```APIDOC ## Core Reference Documentation This section details the core reference documentation files available for the xxl-job-core module. These files cover API references for executors and handlers, context helpers, type definitions, OpenAPI specifications, configuration details, and error codes. ### executor-api.md - **Description**: XxlJobExecutor API reference, including configuration properties, lifecycle methods, handler registration, and admin communication interfaces. - **Content**: Configuration properties (admin, network, logging, GLUE), Lifecycle methods (start, destroy), Handler registration and job thread management, Admin communication interfaces. ### handler-api.md - **Description**: Documentation for the IJobHandler base interface, @XxlJob annotation, and various handler implementations, covering registration and execution flows. - **Content**: IJobHandler base interface, @XxlJob annotation syntax and usage, MethodJobHandler, GlueJobHandler, ScriptJobHandler implementations, Handler registration flow and execution, Timeout, broadcast/shard, and error handling. ### context-helper-api.md - **Description**: Details on XxlJobContext and XxlJobHelper for accessing job information, shard details, logging, and result handling within the execution context. - **Content**: XxlJobContext thread-local execution context, XxlJobHelper static convenience methods, Job info access (ID, params, log info), Shard/broadcast information, Logging and result handling patterns. ### types.md - **Description**: Defines enums and DTOs used within XXL-JOB, including execution strategies, glue types, registration types, and request/response structures. - **Content**: ExecutorBlockStrategyEnum (SERIAL_EXECUTION, DISCARD_LATER, COVER_EARLY), GlueTypeEnum (BEAN, GLUE_GROOVY, GLUE_SHELL, GLUE_PYTHON, etc.), RegistTypeEnum (AUTOMATIC, MANUAL), All request/response DTOs with field documentation, Constants and their usage. ### openapi-reference.md - **Description**: OpenAPI reference for AdminBiz and ExecutorBiz interfaces, detailing HTTP protocols, security, and request/response formats for multi-language client support. - **Content**: AdminBiz interface (callback, registry, registryRemove), ExecutorBiz interface (beat, idleBeat, trigger, kill, log), HTTP protocol details and security, Multi-language client support examples, Request/response payload formats. ### configuration.md - **Description**: Comprehensive guide to XXL-JOB configuration, covering required and optional properties, Spring Boot formats, programmatic configuration, and deployment scenarios. - **Content**: Required configuration (admin addresses, appname, access token), Optional configuration (network, logging, GLUE), Spring Boot properties and YAML formats, Programmatic configuration, Deployment scenarios and validation rules. ### errors.md - **Description**: Catalog of runtime exceptions, HTTP API error responses, and logged errors, along with result codes and debugging techniques for XXL-JOB. - **Content**: RuntimeException catalog (initialization, registration, server errors), HTTP API error responses, Logged errors (execution, communication, scripts), Result codes (200, 500, 502), Debugging techniques and common solutions. ``` -------------------------------- ### Accessing Job Information via XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/handler-api.md Demonstrates how to retrieve key execution details from the `XxlJobContext` using static methods provided by `XxlJobHelper`. These methods are convenient for accessing job ID, parameters, and sharding information within a handler. ```java // Access via XxlJobHelper: // XxlJobHelper.getJobId() - current job ID // XxlJobHelper.getJobParam() - job parameters // XxlJobHelper.getShardIndex() - shard index in broadcast // XxlJobHelper.getShardTotal() - total shards ``` -------------------------------- ### Get Shard Total with XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Retrieves the total number of shards for a broadcast task. Returns -1 if not in a job context, and 1 for non-broadcast jobs. ```java public static int getShardTotal() ``` -------------------------------- ### Get Shard Index with XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Retrieves the shard index for broadcast tasks (0-based). Returns -1 if not in a job context, and 0 for non-broadcast jobs. ```java public static int getShardIndex() ``` -------------------------------- ### Build XXL-JOB Admin Package and Docker Image Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB官方文档.md Commands to build the XXL-JOB admin package and create a Docker image. The Docker build command allows specifying a version tag. ```bash mvn clean package ``` ```bash docker build -t xuxueli/xxl-job-admin:{指定版本} ./xxl-job-admin ``` -------------------------------- ### Dockerfile for Executor Service Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/integration-guide.md This Dockerfile sets up a minimal Java runtime environment for the XXL-Job executor. It copies the application JAR and sets necessary environment variables for connecting to the admin server. ```dockerfile FROM openjdk:11-jre-slim COPY app.jar /app.jar ENV xxl_job_admin_addresses=http://xxl-job-admin:8080 ENV xxl_job_executor_appname=my-service ENV xxl_job_executor_accessToken=secret EXPOSE 8080 9999 ENTRYPOINT ["java", "-jar", "/app.jar"] ``` -------------------------------- ### Get Job Parameter with XxlJobHelper Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/context-helper-api.md Retrieves the parameter string configured for the job in the admin console. Returns null if called outside of a job context. ```java String param = XxlJobHelper.getJobParam(); ``` -------------------------------- ### Executor Block Strategy Enum Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/types.md Defines behavior when a job execution cannot start due to the previous execution still running. Use match() to parse enum by name. ```java public enum ExecutorBlockStrategyEnum { SERIAL_EXECUTION("Serial execution"), DISCARD_LATER("Discard Later"), COVER_EARLY("Cover Early"); private String title; public String getTitle() { ... } public static ExecutorBlockStrategyEnum match(String name, ExecutorBlockStrategyEnum defaultItem) { ... } } ``` ```java ExecutorBlockStrategyEnum strategy = ExecutorBlockStrategyEnum.match("SERIAL_EXECUTION", ExecutorBlockStrategyEnum.SERIAL_EXECUTION); ``` -------------------------------- ### Log Details Explanation Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB官方文档.md Explains the fields available in the task execution logs, including调度时间 (Scheduling Time), 调度结果 (Scheduling Result), 调度备注 (Scheduling Remarks), 执行器地址 (Executor Address), 运行模式 (Execution Mode), 任务参数 (Task Parameters), 执行时间 (Execution Time), 执行结果 (Execution Result), and 执行备注 (Execution Remarks). It also details the actions available like '执行日志' (Execution Log) and '终止任务' (Terminate Task). ```plaintext 调度时间:"调度中心"触发本次调度并向"执行器"发送任务执行信号的时间; 调度结果:"调度中心"触发本次调度的结果,200表示成功,500或其他表示失败; 调度备注:"调度中心"触发本次调度的日志信息; 执行器地址:本次任务执行的机器地址 运行模式:触发调度时任务的运行模式,运行模式可参考章节 "三、任务详解"; 任务参数:本地任务执行的入参 执行时间:"执行器"中本次任务执行结束后回调的时间; 执行结果:"执行器"中本次任务执行的结果,200表示成功,500或其他表示失败; 执行备注:"执行器"中本次任务执行的日志信息; 操作: "执行日志"按钮:点击可查看本地任务执行的详细日志信息;详见“4.8 查看执行日志”; "终止任务"按钮:点击可终止本地调度对应执行器上本任务的执行线程,包括未执行的阻塞任务一并被终止; ``` -------------------------------- ### Configure XxlJob Executor with Spring Configuration Class Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/configuration.md Define a Spring configuration class to programmatically set up the XxlJobSpringExecutor bean. This approach allows for dynamic configuration and dependency injection of values from properties. ```java @Configuration public class XxlJobConfig { @Bean public XxlJobSpringExecutor xxlJobExecutor( @Value("${xxl.job.admin.addresses}") String adminAddresses, @Value("${xxl.job.executor.appname}") String appname, @Value("${xxl.job.executor.accessToken}") String accessToken, @Value("${xxl.job.executor.ip:}") String ip, @Value("${xxl.job.executor.port:0}") int port, @Value("${xxl.job.executor.address:}") String address, @Value("${xxl.job.executor.timeout:3}") int timeout, @Value("${xxl.job.executor.logpath:/data/applogs/xxl-job/jobhandler}") String logpath, @Value("${xxl.job.executor.logretentiondays:30}") int logretentiondays, @Value("${xxl.job.executor.glueEnabled:true}") boolean glueEnabled) { XxlJobSpringExecutor executor = new XxlJobSpringExecutor(); executor.setAdminAddresses(adminAddresses); executor.setAppname(appname); executor.setAccessToken(accessToken); executor.setIp(ip); executor.setPort(port); executor.setAddress(address); executor.setTimeout(timeout); executor.setLogPath(logpath); executor.setLogRetentionDays(logretentiondays); executor.setGlueEnabled(glueEnabled); return executor; } } ``` -------------------------------- ### Create Spring Configuration for XXL-JOB Executor Source: https://github.com/xuxueli/xxl-job/blob/master/_autodocs/integration-guide.md Define a Spring configuration class to set up the XxlJobSpringExecutor bean. ```java @Configuration public class XxlJobConfig { @Bean public XxlJobSpringExecutor xxlJobExecutor() { XxlJobSpringExecutor executor = new XxlJobSpringExecutor(); executor.setAdminAddresses("${xxl.job.admin.addresses}"); executor.setAppname("${xxl.job.executor.appname}"); executor.setAccessToken("${xxl.job.executor.accessToken}"); executor.setLogPath("${xxl.job.executor.logpath}"); return executor; } } ``` -------------------------------- ### Java Cron Trigger with Misfire Handling Source: https://github.com/xuxueli/xxl-job/blob/master/doc/XXL-JOB-English-Documentation.md Example of building a cron trigger in Java with a specific misfire handling policy. Uses 'doNothing' to avoid immediate execution of missed jobs. ```java CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfo.getJobCron()).withMisfireHandlingInstructionDoNothing(); CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build(); ```