package com.hys.app.service.system.task.impl;

import com.hys.app.framework.util.StringUtil;
import com.hys.app.model.base.Result;
import com.hys.app.model.base.ThreadPoolConstant;
import com.hys.app.service.system.task.AsyncExecutor;
import com.hys.app.service.system.task.TaskError;
import com.hys.app.service.system.task.TaskRunnable;
import com.hys.app.service.system.task.ThreadHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 异步执行器
 *
 * @author 张崧
 * 2023-05-12
 */
@Service
@Slf4j
public class AsyncExecutorImpl implements AsyncExecutor {

    @Override
    @Async(ThreadPoolConstant.COMMON_POOL)
    public void execute(ThreadHandler onStart, TaskRunnable runnable, Runnable onSuccess, TaskError onError) {
        if (onStart != null) {
            onStart.run(Thread.currentThread());
        }
        try {
            Result result = runnable.run();
            if (result.getSuccess() && onSuccess != null) {
                onSuccess.run();
            }
            if (!result.getSuccess() && onError != null) {
                onError.onError(null, result.getRemark());
            }

        } catch (Exception e) {
            log.error("异步任务执行出错", e);
            if (onError != null) {
                onError.onError(e, StringUtil.formatException(e));
            }
        }
    }
}
