如何通过轮询检查智能卡是否存在

How to check smartcard presence by polling

我需要检查我的 Java 应用程序中是否存在智能卡,以便在删除智能卡时生成类似于 "event" 的内容。

我有一个简单的测试方法:

public boolean isCardIn(){};

投票的最佳方式是什么? 在这种情况下,我应该使用 java.utils.Timer.Timer() 还是 ExecutorService()


这是我当前的实现:

开始投票

checkTimer.schedule(new CheckCard(), delay,delay);

这是定时器的执行:

private class CheckCard extends TimerTask{   

    @Override
    public void run() {
        try{
            if(!SmartcardApi.isCardIn(slot)){
                 // fire event
            }
        }catch(Exception e){
        }
    }

}

我会进一步查看 Whosebug,因为我认为您的问题已得到解答: Java Timer vs ExecutorService?

我认为一般来说,最好使用较新的 API,在本例中是 ExecutorService。以下是我的做法:

主要方法

public static void main(String[] args) throws InterruptedException, ExecutionException {
    ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    SmartCardApi smartCardApi = new SmartCardApi();

    // Polling job.
    Runnable job = new Runnable() {
        @Override
        public void run() {
            System.out.println("Is card in slot? " + smartCardApi.isCardInSlot());
        }
    };
    
    // Schedule the check every second.
    scheduledExecutor.scheduleAtFixedRate(job, 1000, 1000, TimeUnit.MILLISECONDS);
    
    // After 3.5 seconds, insert the card using the API.
    Thread.sleep(3500);
    smartCardApi.insert(1);
    
    // After 4 seconds, eject the card using the API.
    Thread.sleep(4000);
    smartCardApi.eject();

    // Shutdown polling job.
    scheduledExecutor.shutdown();
    
    // Verify card status.
    System.out.println("Program is exiting. Is card still in slot? " + smartCardApi.isCardInSlot());
}

SmartCardApi

package test;

import java.util.concurrent.atomic.AtomicBoolean;

public class SmartCardApi {
    private AtomicBoolean inSlot = new AtomicBoolean(false);
    
    public boolean isCardInSlot() {
        return inSlot.get();
    }
    
    public void insert(int slot) {
        System.out.println("Inserted into " + slot);
        inSlot.set(true);
    }

    public void eject() {
        System.out.println("Ejected card.");
        inSlot.set(false);
    }
}

程序输出

Is card in slot? false
Is card in slot? false
Is card in slot? false
Inserted into 1
Is card in slot? true
Is card in slot? true
Is card in slot? true
Is card in slot? true
Ejected card.
Program is exiting. Is card still in slot? false

在这种情况下,我使用了一个简单的 Runnable,它可以调用另一个对象来触发它的 event。您也可以使用 FutureTask 而不是此 Runnable,但这只是基于您对 如何 的偏好,您希望此事件被触发..