How can I terminate a running EC2 instance has not been used for a given period?
How can I check if the EC2 instance is being used or not before terminating?
The hardest part of your requirement is to identify whether an Amazon EC2 instance is "being used".
Amazon EC2 cannot see "inside" the instance, so it does not know whether anybody is logged in, or any processes that are running. You could use CPU Utilization to determine whether it is "being used", but that is not a reliable measure unless usage always involves significant CPU usage.
Alternatively, you could put a script on the EC2 instance that is triggered every few minutes by cron. The script could measure something that indicates "use", such as the number of logged-in users, or perhaps whether a particular process is running.
If you were able to determine whether it is "in use", you could send data to an Amazon CloudWatch metric (eg either a boolean to say it is in-use, or a measure such as the number of users). You could then create an Amazon CloudWatch alarm to trigger after a period of time if the measure is below a desired threshold. The alarm could then Terminate the instance.