001/* 002 * jPOS Project [http://jpos.org] 003 * Copyright (C) 2000-2026 jPOS Software SRL 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Affero General Public License as 007 * published by the Free Software Foundation, either version 3 of the 008 * License, or (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Affero General Public License for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jpos.util; 020 021import java.util.Timer; 022import java.util.TimerTask; 023import java.util.concurrent.atomic.AtomicLong; 024 025 026/** 027 * WatchDog will issue a warning message 028 * if not canceled on time 029 */ 030@SuppressWarnings("unused") 031public class WatchDog extends TimerTask { 032 String message; 033 String logName; 034 String realm; 035 private static Timer timer = new Timer(true); 036 private static AtomicLong counter = new AtomicLong(0L); 037 /** Number of timer schedules between proactive cancellation purges. */ 038 public static long PURGE_INTERVAL = 1000L; 039 040 /** 041 * Schedules a silent watchdog that fires after {@code duration} milliseconds. 042 * 043 * @param duration delay in milliseconds before {@link #run()} fires 044 */ 045 public WatchDog (long duration) { 046 timer.schedule(this, duration); 047 if (counter.incrementAndGet() % PURGE_INTERVAL == 0) 048 timer.purge(); // pro-active purge due to excessive number of timertask cancels. 049 } 050 /** 051 * Schedules a watchdog that, if not cancelled in time, logs {@code message} as a warning. 052 * 053 * @param duration delay in milliseconds before {@link #run()} fires 054 * @param message warning message to log when the timer expires 055 */ 056 public WatchDog (long duration, String message) { 057 this(duration); 058 this.logName = "Q2"; 059 this.realm = "watchdog"; 060 this.message = message; 061 } 062 /** 063 * Overrides the logger name used for the warning. 064 * 065 * @param logName logger name (defaults to {@code Q2}) 066 */ 067 public void setLogName (String logName) { 068 this.logName = logName; 069 } 070 /** 071 * Overrides the realm used for the warning. 072 * 073 * @param realm logger realm (defaults to {@code watchdog}) 074 */ 075 public void setRealm (String realm) { 076 this.realm = realm; 077 } 078 /** Logs the configured message at warning level when the timer expires. */ 079 public void run () { 080 if (message != null) 081 Log.getLog (logName, realm).warn (message); 082 } 083}