View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.data.pipeline.core.listener;
19  
20  import lombok.extern.slf4j.Slf4j;
21  import org.apache.shardingsphere.elasticjob.infra.listener.ElasticJobListener;
22  import org.apache.shardingsphere.elasticjob.infra.listener.ShardingContexts;
23  
24  import java.util.Map;
25  import java.util.concurrent.ConcurrentHashMap;
26  
27  /**
28   * Pipeline elastic job listener.
29   */
30  @Slf4j
31  public final class PipelineElasticJobListener implements ElasticJobListener {
32      
33      // TODO ElasticJobListenerFactory.createListener return new class instance, it's the reason why static variables
34      private static final Map<String, Long> RUNNING_JOBS = new ConcurrentHashMap<>();
35      
36      @Override
37      public void beforeJobExecuted(final ShardingContexts shardingContexts) {
38          if (RUNNING_JOBS.containsKey(shardingContexts.getJobName())) {
39              log.warn("{} already exists", shardingContexts.getJobName());
40          }
41          RUNNING_JOBS.put(shardingContexts.getJobName(), System.currentTimeMillis());
42      }
43      
44      @Override
45      public void afterJobExecuted(final ShardingContexts shardingContexts) {
46          log.info("After {} job execute ", shardingContexts.getJobName());
47          RUNNING_JOBS.remove(shardingContexts.getJobName());
48      }
49      
50      /**
51       * Is job running.
52       *
53       * @param jobId job id
54       * @return true if job is running otherwise false
55       */
56      public boolean isJobRunning(final String jobId) {
57          return RUNNING_JOBS.containsKey(jobId);
58      }
59      
60      @Override
61      public String getType() {
62          return PipelineElasticJobListener.class.getName();
63      }
64  }